87,992
社区成员
发帖
与我相关
我的任务
分享
以的想法是:接收图片路径时先判断图片格式,然后修改为正确的后缀。 以下是我的代码。
enum ImageType{
jpg,
bmp,
png,
gif,
nothing
};
ImageType image_type(const std::string &path)
{
std::ifstream inFile(path.c_str());
unsigned char png_type[9] = {0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,'/0'};
unsigned char gif_type[7] = {0x47,0x49,0x46,0x38,0x39/*0x37*/,0x61,'/0'};
unsigned char file_head[9];
for (int i=0;i<8;++i)
{
inFile>>file_head[i];
}
file_head[8] = '/0';
switch (file_head[0])
{
case 0xff:
if (file_head[1]==0xd8)
return jpg;//jpeg
case 0x42:
if (file_head[1]==0x4D)
return bmp;//bmp
case 0x89:
if (file_head[1]==png_type[1] && file_head[2]==png_type[2] && file_head[3]==png_type[3] && file_head[4]==png_type[4]&&
file_head[5]==png_type[5] && file_head[6]==png_type[6] && file_head[7]==png_type[7])
return png;//png
case 0x47:
if (file_head[1]==gif_type[1] && file_head[2]==gif_type[2] && file_head[3]==gif_type[3] && file_head[5]==gif_type[5]
&& ( file_head[4]==0x39 || file_head[4]==0x37 ))
return gif; //gif
default:
return nothing;
}
}
bool ModPicname(const std::string &src)
{
ImageType mType = image_type(src);
std::string url = src;
std::string::size_type iPos = url.find_last_of(".");
if (std::string::npos != iPos)
{
switch(mType)
{
case jpg:
url.replace(iPos+1, iPos+1, "jpg");
break;
case bmp:
url.replace(iPos+1, iPos+1, "bmp");
break;
case png:
url.replace(iPos+1, iPos+1, "png");
break;
case gif:
url.replace(iPos+1, iPos+1, "gif");
break;
default:
break;
}
}
if (!url.empty())
{
if (0 != rename(src.c_str(), url.c_str()))
{
return false;//修改图片名失败!
}
}
return true;
}
现在有疑问,png需要判断8位文件头,用UltraEdit打开看图片也确实是png的,为什么后4位总是取得不对? 求解。


服务器给的图片,他们也不肯改。