文章來源: CSDN博客
//C#快速獲取JPG圖片大小及英寸分辨率
public static int getJpgSize(string FileName, out Size JpgSize, out float Wpx, out float Hpx)
{//C#快速獲取JPG圖片大小及英寸分辨率
JpgSize = new Size(0, 0);
Wpx = 0; Hpx = 0;
int rx = 0;
if (!File.Exists(FileName)) return rx;
FileStream F_Stream = File.OpenRead(FileName);
int ff = F_Stream.ReadByte();
int type = F_Stream.ReadByte();
if (ff != 0xff || type != 0xd8)
{//非JPG文件
F_Stream.Close();
return rx;
}
long ps = 0;
do
{
do
{
ff = F_Stream.ReadByte();
if (ff < 0) //文件結束
{
F_Stream.Close();
return rx;
}
} while (ff != 0xff);
do
{
type = F_Stream.ReadByte();
} while (type == 0xff);
//MessageBox.Show(ff.ToString() + "," + type.ToString(), F_Stream.Position.ToString());
ps = F_Stream.Position;
switch (type)
{
case 0x00:
case 0x01:
case 0xD0:
case 0xD1:
case 0xD2:
case 0xD3:
case 0xD4:
case 0xD5:
case 0xD6:
case 0xD7:
break;
case 0xc0: //SOF0段
ps = F_Stream.ReadByte() * 256;
ps = F_Stream.Position + ps + F_Stream.ReadByte() - 2; //加段長度
F_Stream.ReadByte(); //丟棄精度數據
//高度
JpgSize.Height = F_Stream.ReadByte() * 256;
JpgSize.Height = JpgSize.Height + F_Stream.ReadByte();
//寬度
JpgSize.Width = F_Stream.ReadByte() * 256;
JpgSize.Width = JpgSize.Width + F_Stream.ReadByte();
//后面信息忽略
if (rx!=1 && rx < 3) rx = rx + 1;
break;
case 0xe0: //APP0段
ps = F_Stream.ReadByte() * 256;
ps = F_Stream.Position + ps + F_Stream.ReadByte() - 2; //加段長度
F_Stream.Seek(5,SeekOrigin.Current); //丟棄APP0標記(5bytes)
F_Stream.Seek(2,SeekOrigin.Current); //丟棄主版本號(1bytes)及次版本號(1bytes)
int units=F_Stream.ReadByte(); //X和Y的密度單位,units=0:無單位,units=1:點數/英寸,units=2:點數/厘米
//水平方向(像素/英寸)分辨率
Wpx=F_Stream.ReadByte()*256;
Wpx=Wpx+F_Stream.ReadByte();
if (units == 2) Wpx = (float)(Wpx * 2.54); //厘米變為英寸
//垂直方向(像素/英寸)分辨率
Hpx = F_Stream.ReadByte() * 256;
Hpx = Hpx + F_Stream.ReadByte();
if (units == 2) Hpx = (float)(Hpx * 2.54); //厘米變為英寸
//后面信息忽略
if (rx!=2 && rx<3) rx = rx + 2;
break;
default: //別的段都跳過////////////////
ps = F_Stream.ReadByte() * 256;
ps = F_Stream.Position + ps + F_Stream.ReadByte() - 2; //加段長度
break;
}
if (ps + 1 >= F_Stream.Length) //文件結束
{
F_Stream.Close();
return rx;
}
F_Stream.Position = ps; //移動指針
} while (type != 0xda); // 掃描行開始
F_Stream.Close();
return rx;
}
我最近在玩和訊微博,很方便,很實用,你也來和我一起玩吧!
去看看我的微博吧!http://t.hexun.com/4194019/default.html