c++获取图像的长宽 opencv_C++实现读取图片长度和宽度

本文介绍了一个C++类CImage,用于读取图像文件的宽度和高度。通过检查文件扩展名确定图像类型,然后解析不同格式(如gif、jpg、png和bmp)的文件头来获取图像的长宽。
部署运行你感兴趣的模型镜像

#include

#include

#include

using namespace std;

class CImage

{

private:

long m_Width;

long m_Height;

int get_extension(string fname);

public:

CImage()

{

m_Width = 0;

m_Height = 0;

};

void LoadImage(char* fname);

long get_width()

{

return m_Width;

};

long get_height()

{

return m_Height;

};

};

int CImage::get_extension(string fname)

{

char c = fname.at(fname.length()-1);

char c2 = fname.at(fname.length()-3);

if ((c == 'f') && (c2 == 'g')){ // file extension name is gif

return 1;

}else if ((c == 'g') && (c2 == 'j')){ // file extension name is jpg

return 2;

}else if ((c == 'g') && (c2 == 'p')){ // file extension name is png

return 3;

}else if ((c == 'p') && (c2 == 'b')){ // file extension name is bmp

return 4;

}

return 0;

}

void CImage::LoadImage(char *fname)

{

m_Width = m_Height = 0;

ifstream ffin(fname, std::ios::binary);

if (!ffin){

cout<

return;

}

int result = get_extension(fname);

char s1[2] = {0}, s2[2] = {0};

switch(result)

{

case 1: // gif

ffin.seekg(6);

ffin.read(s1, 2);

ffin.read(s2, 2);

m_Width = (unsigned int)(s1[1])<<8|(unsigned int)(s1[0]);

m_Height = (unsigned int)(s2[1])<<8|(unsigned int)(s2[0]);

break;

case 2: // jpg

ffin.seekg(164);

ffin.read(s1, 2);

ffin.read(s2, 2);

m_Width = (unsigned int)(s1[1])<<8|(unsigned int)(s1[0]);

m_Height = (unsigned int)(s2[1])<<8|(unsigned int)(s2[0]);

break;

case 3: // png

ffin.seekg(17);

ffin.read(s1, 2);

ffin.seekg(2, std::ios::cur);

ffin.read(s2, 2);

m_Width = (unsigned int)(s1[1])<<8|(unsigned int)(s1[0]);

m_Height = (unsigned int)(s2[1])<<8|(unsigned int)(s2[0]);

break;

case 4: // bmp

ffin.seekg(18);

ffin.read(s1, 2);

ffin.seekg(2, std::ios::cur);

ffin.read(s2, 2);

m_Width = (unsigned int)(s1[1])<<8|(unsigned int)(s1[0]);

m_Height = (unsigned int)(s2[1])<<8|(unsigned int)(s2[0]);

break;

default:

cout<

break;

}

ffin.close();

};

int main(int argc, char *argv[])

{

if (argc < 2){

printf("usage: program imagefilename/n");

return 0;

}

CImage test;

test.LoadImage(argv[1]);

cout<

cout<

return 0;

}

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值