How to reduce the size of an image in C# and .NET 3.5?

后端 未结 7 1532
忘掉有多难
忘掉有多难 2020-12-05 16:10

I have a screen shot I take in my mobile app. The screen shot takes about 32 KB when saved as a png on a disk.

I am sending these to a central SQL Server and 32 KB

7条回答
  •  日久生厌
    2020-12-05 16:50

        private static Image ResizeImage(int newSize, Image originalImage)
        {
            if (originalImage.Width <= newSize)
                newSize = originalImage.Width;
    
            var newHeight = originalImage.Height * newSize / originalImage.Width;
    
            if (newHeight > newSize)
            {
                // Resize with height instead
                newSize = originalImage.Width * newSize / originalImage.Height;
                newHeight = newSize;
            }
    
            return originalImage.GetThumbnailImage(newSize, newHeight, null, IntPtr.Zero);
        }
    

    This should work with your Bitmap object Type and resize the Height or Width, depending on which is appropriate for your image dimensions. It will also maintain scale.

    EDIT:

    You could create a new Bitmap object and resize your original image into that Bitmap object.

    Bitmap b = new Bitmap(newWidth, newHeight);
    Graphics g = Graphics.FromImage((Image)b);
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    
    g.DrawImage(imgToResize, 0, 0, newWidth, newHeight);
    g.Dispose();
    
    return (Image)b;
    

    I don't have the Compact Framework installed, but it seems that this should work for you.

提交回复
热议问题