C#图片处理之:保存原始Exif到处理过的JPEG图片中

自从越来越多的兄弟姐妹买了单反,亮骚就是不可避免的了,处理过的图片丢失Exif信息未免有些遗憾。而且从正儿八经的角度看,查看Exif确实是总结拍摄经验吸取教训寻找问题的一个很有效地手段。因此还是研究了下如何保存原始Exif到处理过的JPEG图片中。

我的方案很简单,从原始图中原封不动的提取Exif信息,然后在保存前还给Bitmap就行。参考代码如下:

  1. public List<PropertyItem> GetImageProperties(string FileName)
  2. {
  3. if (!File.Exists(FileName)) returnnull;
  4. List<PropertyItem> rtn = new List<PropertyItem>();
  5. Image img = null;
  6. try
  7. {
  8. img = Image.FromFile(FileName);
  9. PropertyItem[] pt = img.PropertyItems;
  10. foreach (PropertyItem p in pt)
  11. {
  12. rtn.Add(p);
  13. }
  14. }
  15. catch
  16. {
  17. rtn = null;
  18. }
  19. finally
  20. {
  21. if (img != null) img.Dispose();
  22. }
  23. return rtn;
  24. }
  25. publicbool SaveAsJPEG(Bitmap bmp, string FileName, int Qty, List<PropertyItem> Exif)
  26. {
  27. try
  28. {
  29. // 在这里设置EXIF
  30. foreach (PropertyItem pitem in Exif)
  31. {
  32. bmp.SetPropertyItem(pitem);
  33. }
  34. EncoderParameter p;
  35. EncoderParameters ps;
  36. ps = new EncoderParameters(1);
  37. p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
  38. ps.Param[0] = p;
  39. bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps);
  40. returntrue;
  41. }
  42. catch (Exception ex)
  43. {
  44. //string x = ex.Message;
  45. returnfalse;
  46. }
  47. }

处理图片时常用的过程是:读入图片文件并转化为Bitmap -> 处理此Bitmap的每个点以得到需要的效果 -> 保存新的Bitmap到文件

使用C#很方便的就可以把多种格式的图片文件读到Bitmap对象中。一句话就够了,常见的格式都支持,诸如JPEG,BMP,PNG等等。

Bitmap bmp = new Bitmap("文件名");

然后就是怎么处理这个图片的问题了,与本案无关,pass。

最后就是保存。JPEG虽然是有损压缩方案,但是它在缩减文件体积和尽可能好的保留原有信息的矛盾上很好的找到了平衡点,所以在很多情况下成为首选的保存方案。

C#当然不会无视这一点,Bitmap类提供了默认的另存为JPEG的方法:

bmp.Save("输出文件", System.Drawing.Imaging.ImageFormat.Jpeg);

这样当然很方便,但有时候更在乎文件体积而有时候更在乎图像质量,是不是有什么办法可以让自己来控制压缩质量呢?

答案是肯定的,bmp.Save方法中有个重载用到了EncoderParameters参数。我们可以在这个参数中加入自己的控制质量。

{

return false;

}

}