PHP批量修改圖片DPI

<?php
for($i = 1; $i<= 30000; $i ++){
    $name = substr('0000' . $i, -5);
    $pic = 'C' . $name . '.png';
    convertDPI($pic);
}

function convertDPI($filename){
    $file = file_get_contents($filename);
 
    //數據塊長度爲9
    $len = pack("N", 9);
    //數據塊類型標誌爲pHYs
    $sign = pack("A*", "pHYs");
    //X方向和Y方向的分辨率均爲300DPI(1像素/英寸=39.37像素/米),單位爲米(0爲未知,1爲米)
    $data = pack("NNC", 300 * 39.37, 300 * 39.37, 0x01);
    //CRC檢驗碼由數據塊符號和數據域計算得到
    $checksum = pack("N", crc32($sign . $data));
    $phys = $len . $sign . $data . $checksum;
     
    $pos = strpos($file, "pHYs");
    if ($pos > 0) {
        //修改pHYs數據塊
        $file = substr_replace($file, $phys, $pos - 4, 21);
    } else {
        //IHDR結束位置(PNG頭固定長度爲8,IHDR固定長度爲25)
        $pos = 33;
        //將pHYs數據塊插入到IHDR之後
        $file = substr_replace($file, $phys, $pos, 0);
    }

    file_put_contents('300DPI/' . $filename, $file);
}

?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章