Compress image in .NET

折月煮酒 提交于 2019-12-30 07:12:29

问题


How can i compress and image file(*bmp,*jpeg) in C#, I have to display some images as background on my controls, i m using following code to scale my image

Bitmap orgBitmap = new Bitmap(_filePath);
Bitmap regBitmap = new Bitmap(reqSize.Width, reqSize.Height);

 using (Graphics gr = Graphics.FromImage(reqBitmap))
 {
  gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
  gr.DrawImage(bmp, new RectangleF(0, 0, reqSize.Width, reqSize.Height));
  }

It giving me the required bitmap. My problem is if orginal bitmap is to heavy(2 MB) then when i load 50 image it feed all my memory, i want to compress the image as much i can without losing the so much quality,How can i do the same in .NET ?


回答1:


Do you definitely need the large images to be present at execution time? Could you resize them (or save them at a slightly lower quality) using an image editing program (Photoshop, Paintshop Pro etc) beforehand? There seems to be little point in doing the work every time you run - especially as editing tools are likely to do a better job anyway.

Of course, this won't work if it's something like the user picking arbitrary images from their hard disk.

Another point: are you disposing of the bitmaps when you're finished with them? You aren't showing that in your code... if you're not disposing of the original (large) bitmaps then you'll be at the mercy of finalizers to release the unmanaged resources. The finalizers will also delay garbage collection of those objects.




回答2:


JPEG always lose something, PNG don't.

This is how you encode and decode PNG with C#:
http://msdn.microsoft.com/en-us/library/aa970062.aspx




回答3:


Perhaps I'm misunderstanding things, but why not convert the bitmaps to jpg's before you import them into your project as control backgrounds?




回答4:


Good luck compressing JPEG. :) It's compressed already. As for your BMPs, make them JPEGs.



来源:https://stackoverflow.com/questions/1377438/compress-image-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!