Sponsored Ad

Wednesday, March 24, 2010

How to convert image to Thumbnail Image in C#

These are three utilities to convent  a given image to a thumbnail image.

this utility only take the full size image in byte format and convert into the given height and width thumb image.

 

public static byte[] MakeThumb(byte[] fullsize, int newwidth, int newheight)
{
    Image iOriginal, iThumb;
    double scaleH, scaleW;

    Rectangle srcRect=new Rectangle();
    iOriginal = Image.FromStream(new MemoryStream(fullsize));
    scaleH = iOriginal.Height / newheight;
    scaleW = iOriginal.Width / newwidth;
    if (scaleH == scaleW)
    {
        srcRect.Width = iOriginal.Width;
        srcRect.Height = iOriginal.Height;
        srcRect.X = 0;
        srcRect.Y = 0;
    }
    else if ((scaleH) > (scaleW))
    {
        srcRect.Width = iOriginal.Width;
        srcRect.Height = Convert.ToInt32(newheight * scaleW);
        srcRect.X = 0;
        srcRect.Y = Convert.ToInt32((iOriginal.Height - srcRect.Height) / 2);
    }
    else
    {
        srcRect.Width = Convert.ToInt32(newwidth * scaleH);
        srcRect.Height = iOriginal.Height;
        srcRect.X = Convert.ToInt32((iOriginal.Width - srcRect.Width) / 2);
        srcRect.Y = 0;
    }
    iThumb = new Bitmap(newwidth, newheight);
    Graphics g = Graphics.FromImage(iThumb);
    g.DrawImage(iOriginal, new Rectangle(0, 0, newwidth, newheight), srcRect, GraphicsUnit.Pixel);
    MemoryStream m = new MemoryStream();
    iThumb.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
    return m.GetBuffer();
}

 

There is another utility to convert a given image to a thumbinal image just by using a given width.

public static byte[] MakeThumb(byte[] fullsize, int maxwidth)
{
    Image iOriginal, iThumb;
    double scale;

    iOriginal = Image.FromStream(new MemoryStream(fullsize));
    if (iOriginal.Width > maxwidth)
    {
        scale = iOriginal.Width / maxwidth;
        int newheight = Convert.ToInt32(iOriginal.Height / scale);
        iThumb = new Bitmap(iOriginal, maxwidth, newheight);
        MemoryStream m = new MemoryStream();
        iThumb.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
        return m.GetBuffer();
    }
    else
    {
        return fullsize;
    }
}

 

To convert a given image to a byte array you can use the following utility.

 

public byte[] ConvertimageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return  ms.ToArray();
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers