C++ 将文件以十六进制显示、获取png图片的宽和高

前者010editor和HxD软件可以看
后者直接右键单击-属性-详细信息就能看到,鼠标悬停也会有

#include<iostream>
#include<fstream>
#include<string>
#include <iomanip>
#include <cstdint>

using namespace std;

/// @brief 文件以十六进制显示
/// @param filePath 文件路径
/// @param bytes_pre_line 每行显示字节数,默认为16
/// @param read_bytes 从文件头开始读取的字节总数,默认为0读取整个文件
void showHex(std::string filePath, unsigned int bytes_pre_line=16, unsigned long read_bytes=0)
{
    std::ifstream fs;
    fs.open(filePath, ios_base::binary|ios::ate);
    if(!fs)
    {
        std::cerr << "无法打开文件" << std::endl;
        exit(1);
    }
    unsigned long ReadBytes;
    if(read_bytes)
    {
        ReadBytes = read_bytes;
    } else 
    {
        // fs.seekg(0, ios::end);
        ReadBytes = fs.tellg();
    }
    fs.seekg(0, ios::beg);
    char byte;
    int i,nn=0;
    std::string buf;
    for(i=1;i<=ReadBytes;++i)
    {
        fs.get(byte);
        buf += isprint(byte) ? byte : '.';
        nn = (int)(byte) & 0xff;
        std::cout << std::setfill('0') << std::setw(2) << std::hex << nn << " ";
        if(i%bytes_pre_line==0)
        { 
            std::cout << " |  " << buf << std::endl; 
            buf = "";
        }
    }
    if(i%bytes_pre_line != 1)
    {
        while(true)
        {
            std::cout << "   ";
            if(i%bytes_pre_line==0)
            { 
                std::cout << " |  " << buf << std::endl; 
                break;
            }
            ++i;
        }
    }
    fs.close();
}
/// @brief 对uint32_t按字节反转
/// @param x uint32_t *
void reverseBytes(uint32_t *x){
    *x = (*x << 16) | (*x >> 16);
    *x = ((*x & 0xff00ff00) >> 8) | ((*x & 0x00ff00ff) << 8);
}

/// @brief 获取PNG文件的宽和高
/// @param filePath PNG文件路径
/// @param width PNG文件的宽
/// @param height PNG文件的高
void getPngWidthHeight(std::string filePath, unsigned int * width, unsigned int * height)
{
    std::ifstream fs;
    fs.open(filePath, ios_base::binary);
    if(!fs)
    {
        std::cerr << "无法打开文件" << std::endl;
        exit(1);
    }
    fs.seekg(16L, ios::beg);
    uint32_t * n;
    fs.read((char *)n, 4);
    reverseBytes(n);  // 如果输出不正确可以试试把这一行去掉
    *width = *n;
    fs.read((char *)n, 4);
    reverseBytes(n);
    *height = *n;
}


int main(){
    unsigned int w,h;
    showHex("0.gif", 8);
    getPngWidthHeight("0.png", &w, &h);
    cout << w << "x" << h << endl;
    return 0;
}

一个示例输出:

47 49 46 38 39 61 01 00  |  GIF89a..
01 00 00 ff 00 2c 00 00  |  .....,..
00 00 01 00 01 00 00 02  |  ........
00 3b                    |  .;
512x711
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今夕何夕2112

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值