Skip to main content
 首页 » 编程设计

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

2024年02月05日29hnrainll

有没有人有将来自 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() 方法保持纵横比。您可能不需要它,并且您可能还想更改参数,以便您可以更改指定如何调整大小的方式。试一试,让我知道效果如何。