c# - 减少来自 HttpPostedFileBase 的图像大小(物理和尺寸)然后转换为 base64

标签 c# image

有没有人有将来自 HttpPostedFileBase 的图像文件转换为缩小尺寸,然后将图像转换为 base64 的好示例?我已经花了几个小时在这上面没有任何运气。这是我的代码的开始。其中一些是硬编码的(图像大小)。

当我将 base64 放在图像标签中并在浏览器中查看时,这会给我一个黑色图像。

    public ActionResult Upload(HttpPostedFileBase file, decimal? id, decimal? id2)
    {                        
            Image img = Image.FromStream(file.InputStream, true, true);

            var bitmap = new Bitmap(img.Width - 100, img.Height - 100);

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] imageBytes = stream.ToArray();
            string base64String = Convert.ToBase64String(imageBytes);
            InsertImage(base64String);
     }

我问的是如何更改图像然后将其转换为 base64。这比称为重复的问题更具体。

最佳答案

我自己从未使用过 HttpPostedFileBase。所以,我稍微简化了这个问题,这实际上是你在以后的问题中应该尝试做的。你应该尽量缩小焦点。也就是说,这里有一种方法可以减少由流表示的图像的维度,并将新图像作为字节数组返回。

    private static byte[] ReduceSize(FileStream stream, int maxWidth, int maxHeight)
    {
        Image source = Image.FromStream(stream);
        double widthRatio = ((double)maxWidth) / source.Width;
        double heightRatio = ((double)maxHeight) / source.Height;
        double ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio;
        Image thumbnail = source.GetThumbnailImage((int)(source.Width * ratio), (int)(source.Height * ratio), AbortCallback, IntPtr.Zero);
        using (var memory = new MemoryStream())
        {
            thumbnail.Save(memory, source.RawFormat);
            return memory.ToArray();
        }
    }

你可以像这样调用这个方法:

public ActionResult Upload(HttpPostedFileBase file, decimal? id, decimal? id2)
{
    byte[] imageBytes = ReduceSize(file.InputStream, 100, 100);
    string base64String = Convert.ToBase64String(imageBytes);
    InsertImage(base64String);
}

我的 ReduceSize() 方法保持纵横比。您可能不需要它,并且您可能还想更改参数,以便您可以更改指定如何调整大小的方式。试一试,让我知道效果如何。

关于c# - 减少来自 HttpPostedFileBase 的图像大小(物理和尺寸)然后转换为 base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792626/

相关文章:

c# - 我可以使用 Roslyn 进行编译时代码重写吗?

java - JLabel 中刷新图像不起作用

python - 如何在Python中将任何图像转换为CV_32FC1

css - 带有链接的悬停图像缩放

c# - 如何获取 XML 格式的 SOAP header ?

c# - 在线问卷/考试申请的设计帮助

c# - 为什么 WPF Presentation 库在 StringBuilder.ToString() 中包装字符串?

c# - 从 C# 中的不同项目写入控制台应用程序项目

c# - WPF图片控件源码

html - 在线显示图片