Showing posts with label Image. Show all posts
Showing posts with label Image. Show all posts

Sunday, August 4, 2013

Lossless Image Compression in C#.Net and VB.Net

Last time I shared C# code which can resize an image with desired size by keeping same Height vs. Width ratio. Now I am going to share next step of image processing code, which can compress an image without (almost) losing it quality. 

Usually an image which you may have taken from one 10 Mega pixel digital camera generates image around 5MB file size. To store same size in webserver and showing it in user’s desktop will slowdown users website browsing experience. For that reason now all website especially photo sharing and social network websites, like facebook.com or google plus etc. compress these images in smaller file size without losing image quality and store in webserver. This technique saves webserver storage and saves network bandwidth when user opens these.

Here I am sharing one method which has written in C# and VB.Net code (base code found somewhere in google then I updated as I need). This method can invoke by just one single line of code and can get compressed image.


How can I use this code in my application?


To use/invoke this method:

CompressJPEGImage(Bitmap Image, Image Name With Full Path)

To use this method you need to create an object of the class where you will define this method and then need call it with parameters ‘image object’ and ‘image full name with path’ where compressed will be saved. On successful compression this method will return 'true' else 'false'.

In my application I have written two overload methods to save the compress image and sometimes to get compressed image object as a return of the method as based on my requirement. 

Full code in C#.Net as below:

  public bool CompressJPEGImage(Bitmap bmp1, string tempImgNameWithPath)

    {
        ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

        // for the Quality parameter category.
        System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;

        EncoderParameters myEncoderParameters = new EncoderParameters(1);
        EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 75L);
        myEncoderParameters.Param[0] = myEncoderParameter;
        try
        {
            bmp1.Save(tempImgNameWithPath, jgpEncoder, myEncoderParameters);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

Full code in VB.Net as below:

Public Function CompressJPEGImage(bmp1 As Bitmap, tempImgNameWithPath As String) As Boolean
 Dim jgpEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)

 ' for the Quality parameter category.
 Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality

 Dim myEncoderParameters As New EncoderParameters(1)
 Dim myEncoderParameter As New EncoderParameter(myEncoder, 75L)
 myEncoderParameters.Param(0) = myEncoderParameter
 Try
  bmp1.Save(tempImgNameWithPath, jgpEncoder, myEncoderParameters)
  Return True
 Catch generatedExceptionName As Exception
  Return False
 End Try
End Function


How can I change image quality and generated size based on my requirement?

For my application I have compressed 75% (75L) but you can change it as per your requirement. If you increase this value then file size and image quality both will increase. Run this code with different parameter value and get image as per your requirement.

Thanks for reading my blog I hope this code will help you to write code.

Sunday, July 28, 2013

Lossless image resize in C# by keeping same aspect ratio.

Now I am developing an image sharing and Indian social network application (www.Alap.Me) where I need to resize image (JPG for my case). This is a very common situation to all coders and it helps us if we get some readymade method which can serve our purpose. I found basic code of this somewhere from Google and later I modified it as I need and finally developed this code.
This code can resize any image by keeping aspect ratio, so your image always will be same in width vs. height ratio.

How to use it?


This is very easy to use this code; just you need to call it with image file name with full path and maximum height and width. My code automatically detects height or width, which is maximum at your parameter and based on this, code will set another parameter based on aspect ratio and finally resize your image.

ResizeImage(fileLocationWithName, maxWidth, maxHeight);

Complete Code in C#.Net


   public Bitmap ResizeImage(string fileNameWithPath, int maxWidth, int maxHeight)
    {        
        FileStream stream = new FileStream(fileNameWithPath, FileMode.Open);
        Stream streamImage = (Stream)stream;
        Bitmap originalImage = new Bitmap(streamImage);
        int newWidth = originalImage.Width;
        int newHeight = originalImage.Height;
        double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
         if (aspectRatio > 1 && originalImage.Width > maxWidth)
        {            
            newWidth = maxWidth;            newHeight = (int)Math.Round(newWidth / aspectRatio);
        }        
        else 
            if (aspectRatio <= 1 && originalImage.Height > maxHeight)
            {            
                newHeight = maxHeight;            newWidth = (int)Math.Round(newHeight * aspectRatio);
            }         
        Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight);
        Graphics g = Graphics.FromImage(newImage);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;

        g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);         

        originalImage.Dispose();        
        stream.Close();        
        stream.Dispose();        
        return newImage;
    }


Complete code in VB.Net:

Public Function ResizeImage(fileNameWithPath As String, maxWidth As Integer, maxHeight As Integer) As Bitmap
 Dim stream As New FileStream(fileNameWithPath, FileMode.Open)
 Dim streamImage As Stream = DirectCast(stream, Stream)
 Dim originalImage As New Bitmap(streamImage)
 Dim newWidth As Integer = originalImage.Width
 Dim newHeight As Integer = originalImage.Height
 Dim aspectRatio As Double = CDbl(originalImage.Width) / CDbl(originalImage.Height)

 If aspectRatio > 1 AndAlso originalImage.Width > maxWidth Then
  newWidth = maxWidth
  newHeight = CInt(Math.Round(newWidth / aspectRatio))
 ElseIf aspectRatio <= 1 AndAlso originalImage.Height > maxHeight Then
  newHeight = maxHeight
  newWidth = CInt(Math.Round(newHeight * aspectRatio))
 End If

 Dim newImage As New Bitmap(originalImage, newWidth, newHeight)

 Dim g As Graphics = Graphics.FromImage(newImage)
 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear
 g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height)

 originalImage.Dispose()
 stream.Close()
 stream.Dispose()

 Return newImage
End Function

I have compressed attached picture by using my code and see here difference.
This is after re-size (around 30KB)



This is original size photo (around 5MB)

























I hope this will help you to make easier your coding. Thank you for reading my blog.