[精讚] [會員登入]
1829

[PHP] 解析二進位圖片

使用php來解析png圖片,把資料寫在16進位格式

分享此文連結 //n.sfs.tw/15438

分享連結 [PHP] 解析二進位圖片@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2021-10-28 13:49:26 最後編修
2021-10-21 10:38:13 By 張○○
 

要使用php來解析二進位圖片,把他顯示成十六進位格式。

先看輸出

最左邊是位置,從0開始;中間是資料內容(16進位);右邊是對應的字元,不能顯示的字元用.或?表示

以下略,先不管此圖片的架構[1],單純的把二進位檔給讀出來。

<?php

$filesize = filesize('sample.png');  
$fp = fopen('sample.png', 'rb');  
$binary = fread($fp, $filesize);
fclose($fp);

$unpacked = unpack(sprintf('C%d', $filesize), $binary);
$unpacked = array_values($unpacked);

$ii=0;
$out= "";
$txt= "";

foreach($unpacked as $v){
  if($ii%30==0){
    print  $out. " " . $txt ."\n" . sprintf("%04d| ", $ii );
    $out= "";
    $txt= "";
  }
  $out .= sprintf("%02X ", $v );
  if($v >=32)$txt .= chr($v);
  else $txt .= ".";
  $ii++;
}
print $out;
print "\n";

第3~6行 用rb讀檔,把內容存入 $binary變數
第8行 用unpack方式解析, C%d 是用成無正負號數字格式,此部分是參考[2]的解法
第9行 把陣列索引清掉

第21行 把數字轉成16進位大寫 [3]
第22~23行 如果該數字>=32 ,就顯示該數字,否則用'.'來替代

 

如此就可以了。

參考資料

[1] 詳解png文件結構(不確定是否為原作) https://www.cnblogs.com/ECJTUACM-873284962/p/8986391.html

[2] https://stackoverflow.com/questions/38859621/reading-binary-files-in-php

[2] https://stackoverflow.com/questions/37094445/padding-zero-for-hexadecimal-number-in-php

 

END

你可能感興趣的文章

[PHP] 2個程式的觀念 整理2個PHP的程式觀念,參考參考。

[PHP] 台灣身分證號及檢查程式 台灣身分證號及PHP檢查程式

[PHP] codeignitor4+ smarty4 這篇整合 php 的framework codeignitor4 + smarty4。

[PHP] 檢查檔案是否是圖檔 使用getimagesize函數檢查檔案是否是圖檔

[PHP] 移除檔案的UTF8 BOM 移除檔案的UTF8 BOM

[PHP+ci4] codeignitor4 Cache 及 Session 使用 memcached php 的framework codeignitor4 中的cache和session使用memcached

隨機好文

[jQuery] select 元件的取值及給值 html中的元件select,在jquery中要如何使用?

UTF-8 BOM (Byte Order Mark) 的問題 在 Michael Kaplan 那看到 Every character has a story #4: U+feff

[札記] 2016.7~12月札記 札記,只是札記

維修冰箱 維修冰箱

NETCRAFT發現你的網站及作業系統 NETCRAFT可以發現你的網站及作業系統