locked
To save a uploaded image in specific format RRS feed

  • Question

  • User-1569779262 posted

    Hello Everyone,

        How can one save an uploaded image in a specific dimension ie in a particular height, width without distorting actual image?It's very urgent.

    Thanks

      

     

    Thursday, July 8, 2010 11:35 AM

Answers

  • User-1718098015 posted

    OK then you just need to read the image file into bytes and resize it and then save it.Below is the code

     

      If ImgUpload.HasFile Then
    
                Dim pFile As HttpPostedFile = ImgUpload.PostedFile
                Dim iLen As Integer = pFile.ContentLength
                Dim oStream As System.IO.Stream = pFile.InputStream
                Dim bBuffer(iLen) As Byte
                Dim iFile() As Byte
                oStream.Read(bBuffer, 0, iLen)
                iFile = bBuffer
                bBuffer = ResizeImageFile(bBuffer, 45)     
                oStream.Close()
               bBuffer = nothing
    End If 


     

      Public Function ResizeImageFile(ByVal imageFile As Byte(), ByVal targetSize As Integer) As Byte()
            Dim original As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(imageFile))
            Dim targetH As Integer, targetW As Integer
            If original.Height > original.Width Then
                targetH = targetSize
                targetW = targetSize
                'targetW = (int)(original.Width * ((float)targetSize / (float)original.Height)); 
            Else
                targetW = targetSize
                targetH = targetSize
                'targetH = (int)(original.Height * ((float)targetSize / (float)original.Width)); 
            End If
            Dim imgPhoto As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(imageFile))
            ' Create a new blank canvas. The resized image will be drawn on this canvas. 
            Dim bmPhoto As New Bitmap(targetW, targetH, System.Drawing.Imaging.PixelFormat.Format24bppRgb)
            bmPhoto.SetResolution(72, 72)
    
            Dim grPhoto As Graphics = Graphics.FromImage(bmPhoto)
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality
            grPhoto.DrawImage(imgPhoto, New Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, _
            GraphicsUnit.Pixel)
    
            ' REMOVE COMMENTED CODE BELOW TO SAVE TO MEMORY 
            Dim mm As New MemoryStream()
            bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg)
    
            '''' SAVE TO FILE DIRECTLY FROM HERE
            Dim sFileName As String
            sFileName = GetYourFileNameWithFullPath()
            bmPhoto.Save(sFileName, ImageFormat.Bmp)
    
            '''''DISPOSE OF ALL OBJECT 
            original.Dispose()
            imgPhoto.Dispose()
            bmPhoto.Dispose()
            grPhoto.Dispose()
    
            '''''RETRUN THE BUUFER CONTENT
            Return mm.GetBuffer()
        End Function


    Thanks and Regards

    Nirav Vyas

    Please Mark As Answer If found useful

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 9, 2010 7:16 AM

All replies

  • User-1718098015 posted

    HI Geet,

    I had played with this image thing few months back , and in your case if you just want to resize your image you can look out the code below and hopefully it would help you out.

    http://snippets.dzone.com/posts/show/1485

     

    Thanks and Regards

    Nirav Vyas

    Please Mark As Answer If found useful

     

     

     

    Thursday, July 8, 2010 12:44 PM
  • User-474337052 posted
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.IO;
    using System.Drawing;
    using System.Net;
    using System.Drawing.Drawing2D;
    /// <summary>
    /// Summary description for Class2
    /// </summary>
    public class Class2 : AspectRatio
    {
    	public Class2()
    	{
    		//
    		// TODO: Add constructor logic here
    		//
    	}
        public Bitmap GetImage(byte[] imageByte, int width, int height)
        {
            System.Drawing.Image b;
            Bitmap bitMap = null;
            if (imageByte != null && imageByte.Length > 10)
            {
                using (MemoryStream mm = new MemoryStream())
                {
                    mm.Write(imageByte, 0, imageByte.Length);
                    b = System.Drawing.Image.FromStream(mm);
                    WidthAndHeight(b.Width, b.Height, width, height);
                    bitMap = new System.Drawing.Bitmap(b, Width, Height);
                    using (Graphics g = Graphics.FromImage(bitMap))
                    {
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.DrawImage(bitMap, 0, 0, b.Width, b.Height);
                        g.Dispose(); b.Dispose(); mm.Dispose(); GC.Collect();
                    }
                }
            }
            return bitMap;
        }
    }
    public class AspectRatio
    {
        public AspectRatio()
        {
        }
        private int d_Width = 0;
        private int d_Height = 0;
        public int Width
        {
            get { return d_Width; }
            set { d_Width = value; }
        }
        public int Height
        {
            get { return d_Height; }
            set { d_Height = value; }
        }
        /// <summary>
        /// Methord For Calculate Hight and Width
        /// </summary>
        /// <param name="aWidth"></param>
        /// <param name="aHeight"></param>
        /// <param name="dWidth"></param>
        /// <param name="dHeight"></param>
        public void WidthAndHeight(int aWidth, int aHeight, int dWidth, int dHeight)
        {
            double height = aHeight;
            double width = aWidth;
            double rWidht = Convert.ToDouble(dWidth);
            double rHeight = Convert.ToDouble(dHeight);
            int fWidth = 0;
            int fHeight = 0;
            double hRatio = 0.0;
            double vRatio = 0.0;
            if (width > rWidht)
            {
                hRatio = (rWidht / width);
                vRatio = (rHeight / height);
    
                if (vRatio > hRatio)
                {
                    fWidth = Convert.ToInt32((double)width * hRatio);
                    fHeight = Convert.ToInt32((double)height * hRatio);
                }
                else
                {
                    fWidth = Convert.ToInt32((double)width * vRatio);
                    fHeight = Convert.ToInt32((double)height * vRatio);
                }
    
            }
            else if (rWidht > width)
            {
                hRatio = (rWidht / width);
                vRatio = (rHeight / height);
    
                if (vRatio > hRatio)
                {
                    fWidth = Convert.ToInt32((double)width * hRatio);
                    fHeight = Convert.ToInt32((double)height * hRatio);
                }
                else
                {
                    fWidth = Convert.ToInt32((double)width * vRatio);
                    fHeight = Convert.ToInt32((double)height * vRatio);
                }
            }
            else if (height > rHeight)
            {
                hRatio = (rWidht / width);
                vRatio = (rHeight / height);
    
                if (vRatio > hRatio)
                {
                    fWidth = Convert.ToInt32((double)width * hRatio);
                    fHeight = Convert.ToInt32((double)height * hRatio);
                }
                else
                {
                    fWidth = Convert.ToInt32((double)width * vRatio);
                    fHeight = Convert.ToInt32((double)height * vRatio);
                }
            }
            else if (rHeight > height)
            {
                hRatio = (rWidht / width);
                vRatio = (rHeight / height);
    
                if (vRatio > hRatio)
                {
                    fWidth = Convert.ToInt32((double)width * hRatio);
                    fHeight = Convert.ToInt32((double)height * hRatio);
                }
                else
                {
                    fWidth = Convert.ToInt32((double)width * vRatio);
                    fHeight = Convert.ToInt32((double)height * vRatio);
                }
            }
            d_Width = fWidth;
            d_Height = fHeight;
        }
    }
    




    protected void Upload_Click(object sender, EventArgs e)
        {
            Class2 objClass = new Class2();
            System.Drawing.Bitmap b = objClass.GetImage(FileUpload1.FileBytes, 200, 200);
            b.Save(Server.MapPath(FileUpload1.FileName));
        }


    Thursday, July 8, 2010 12:50 PM
  • User-1569779262 posted

    Hi

       Thanks for Reply. But I am storing Image like this:

     if ((btnSave.Text == "Update" && FileUpload1.FileName != "") || btnSave.Text == "Save")
                {               
                    String sp;
                    sp = Server.MapPath("../UploadImg");
                    String fn = FileUpload1.FileName;
                    if (sp.EndsWith("//") == false)
                    {
                        sp += "//";
                    }
                    sp += fn;
                    FileUpload1.PostedFile.SaveAs(sp);
                    strFN = FileUpload1.FileName;               
                }
                cmd.Parameters.Add("@img", SqlDbType.VarChar, 50).Value = strFN;






    Thursday, July 8, 2010 1:59 PM
  • User-1718098015 posted

    OK then you just need to read the image file into bytes and resize it and then save it.Below is the code

     

      If ImgUpload.HasFile Then
    
                Dim pFile As HttpPostedFile = ImgUpload.PostedFile
                Dim iLen As Integer = pFile.ContentLength
                Dim oStream As System.IO.Stream = pFile.InputStream
                Dim bBuffer(iLen) As Byte
                Dim iFile() As Byte
                oStream.Read(bBuffer, 0, iLen)
                iFile = bBuffer
                bBuffer = ResizeImageFile(bBuffer, 45)     
                oStream.Close()
               bBuffer = nothing
    End If 


     

      Public Function ResizeImageFile(ByVal imageFile As Byte(), ByVal targetSize As Integer) As Byte()
            Dim original As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(imageFile))
            Dim targetH As Integer, targetW As Integer
            If original.Height > original.Width Then
                targetH = targetSize
                targetW = targetSize
                'targetW = (int)(original.Width * ((float)targetSize / (float)original.Height)); 
            Else
                targetW = targetSize
                targetH = targetSize
                'targetH = (int)(original.Height * ((float)targetSize / (float)original.Width)); 
            End If
            Dim imgPhoto As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(imageFile))
            ' Create a new blank canvas. The resized image will be drawn on this canvas. 
            Dim bmPhoto As New Bitmap(targetW, targetH, System.Drawing.Imaging.PixelFormat.Format24bppRgb)
            bmPhoto.SetResolution(72, 72)
    
            Dim grPhoto As Graphics = Graphics.FromImage(bmPhoto)
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality
            grPhoto.DrawImage(imgPhoto, New Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, _
            GraphicsUnit.Pixel)
    
            ' REMOVE COMMENTED CODE BELOW TO SAVE TO MEMORY 
            Dim mm As New MemoryStream()
            bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg)
    
            '''' SAVE TO FILE DIRECTLY FROM HERE
            Dim sFileName As String
            sFileName = GetYourFileNameWithFullPath()
            bmPhoto.Save(sFileName, ImageFormat.Bmp)
    
            '''''DISPOSE OF ALL OBJECT 
            original.Dispose()
            imgPhoto.Dispose()
            bmPhoto.Dispose()
            grPhoto.Dispose()
    
            '''''RETRUN THE BUUFER CONTENT
            Return mm.GetBuffer()
        End Function


    Thanks and Regards

    Nirav Vyas

    Please Mark As Answer If found useful

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 9, 2010 7:16 AM
  • User1211441112 posted

    using System.Drawing;
    using System.Drawing.Drawing2D;

            public void ResizeStream(int imageSize, Stream filePath, string outputPath)
            {
                var image = Image.FromStream(filePath);

                int thumbnailSize = imageSize;
                int newWidth, newHeight;

                if (image.Width > image.Height)
                {
                    newWidth = thumbnailSize;
                    newHeight = image.Height * thumbnailSize / image.Width;
                }
                else
                {
                    newWidth = image.Width * thumbnailSize / image.Height;
                    newHeight = thumbnailSize;
                }

                var thumbnailBitmap = new Bitmap(newWidth, newHeight);

                var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
                thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
                thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
                thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

                var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
                thumbnailGraph.DrawImage(image, imageRectangle);

                thumbnailBitmap.Save(outputPath, image.RawFormat);
                thumbnailGraph.Dispose();
                thumbnailBitmap.Dispose();
                image.Dispose();
            }

    then call resize image function as

    ResizeImage(400, File1.FileContent, path);

    Monday, July 12, 2010 3:38 AM