欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

C++实现读取图片长度和宽度

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

看到一个用ASP写的读取图片文件的长度、宽度的程序,感觉有点意思,于是用C++也写了一个。

#include <iostream>
#include <fstream>
#include <string>

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<<"Can not open this file."<<endl;
    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<<"NO"<<endl;
    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<<"width:"<<test.get_width()<<endl;
  cout<<"height:"<<test.get_height()<<endl;
   
  return 0;
}

上一篇:C++实现图的邻接表存储和广度优先遍历实例分析

栏    目:C语言

下一篇:C语言拓展实现Lua sleep函数

本文标题:C++实现读取图片长度和宽度

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/3102.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有