如何在 C# 和 .NET 3.5 中减小图像的大小? [英] How to reduce the size of an image in C# and .NET 3.5?

查看:25
本文介绍了如何在 C# 和 .NET 3.5 中减小图像的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在我的移动应用程序中截取的屏幕截图.在磁盘上保存为 png 时,屏幕截图大约需要 32 KB.

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.

我将这些内容发送到中央 SQL Server,但 32 KB 太大了,我需要存储该屏幕截图(每天大约 2500 次).

I am sending these to a central SQL Server and 32 KB is too big for that amount of times I will need to store that screen shot (approx 2500 times a day).

有什么技巧可以让我节省更多的钱吗?

Is there any kind of trickery that I can do to get it to save smaller?

这是我现在使用的代码,用于将其从 Bitmap 转换为字节(发送到服务器进行存储):

Here is the code I am using now to take it from Bitmap to bytes (to send to the server for storage):

MemoryStream stream = new MemoryStream();
 _signatureImage.Save(stream, ImageFormat.Png);
 return stream.ToArray();

_signatureImage 是一个 Bitmap 并且是有问题的屏幕截图.

_signatureImage is a Bitmap and is the screenshot in question.

这是我正在保存的屏幕截图示例:

Here is an example of the screen shot I am saving:

突然想到的事情(但我不知道该怎么做):

Things that pop to mind (but I don't know how to do them):

  1. 减少图像的实际高度和宽度(但希望以一种不会扭曲它的方式).
  2. 将其更改为黑白图像(不确定我是否会从中看到任何真正的空间节省)
  3. 再压缩一下(我不太喜欢这样,因为这样就无法从数据库中读取了).

请注意,这一切都必须以编程方式完成,而且不会花费很长时间,因此不需要进行复杂的图像处理.

Note, this all has to be done programatically, and cannot take very long, so complex image manipulations are out.

感谢您的帮助.

推荐答案

    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.

您可以创建一个新的 Bitmap 对象并将原始图像的大小调整为该 Bitmap 对象.

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;

我没有安装 Compact Framework,但它似乎适合你.

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

这篇关于如何在 C# 和 .NET 3.5 中减小图像的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆