Showing posts with label Quality. Show all posts
Showing posts with label Quality. Show all posts

Thursday, August 13, 2009

.NET Image Manipulation programmatically

Sometimes developer need to do image manipulation pro grammatically:
  1. Resizing the image width/height.
  2. Change image format.
  3. Decrease image quality to decrease image size.
Code Below will help developers to do these tasks:
  1. We will declare variable for new image width, height, Quality(1-100), extension.
  2. Create Bitmap from physical file or stream.



  3. // Create a bitmap from the stream
    Bitmap oldImage = new Bitmap(filename);

  4. Initialize new bitmap using new width and height.


  5. // Initialize new bitmap using new width and height.
    Bitmap newImage = new Bitmap(Width,Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
  6. Initialize graphic from new image.
  7. Draw old image with new width and height to new image variable.

  8. Graphics g = Graphics.FromImage(newImage);
    g.DrawImage(oldImage,0,0,newImage.Width,newImage.Height);
  9. Before we save image we need get encoder of its new type.

  10. private ImageCodecInfo GetEncoderInfo(String mimeType)
    {
    ImageCodecInfo[] encoders;
    encoders = ImageCodecInfo.GetImageEncoders();
    for(int _iLoop = 0; _iLoop<encoders.Length; ++j)
    {
    if(encoders[_iLoop].MimeType == mimeType)
    {
    return encoders[_iLoop];
    }
    }
    return null;
    }
  11. Last step will save image with its new configurations:


  12. EncoderParameters imgParams = new EncoderParameters(1);
    imgParams.Param[0] = new
    EncoderParameter(System.Drawing.Imaging.Encoder.Quality,Quality);
    ImageCodecInfo ici = GetEncoderInfo(sMime);
    ImageCodecInfo newici = GetEncoderInfo(sNewMime);
    imgBitMap.Save(newstream, newici,imgParams);