从流中更改图像大小

5

我在这里搜索帮助,但是没有找到完全符合我需求的内容。我有一个被上传的图像,我想在保存到Azure之前改变它的大小。

目前我的代码是:

public ActionResult UserDetails(HttpPostedFileBase photo)
    {     var inputFile = new Photo()
            {
                FileName = photo.FileName,                    
                Data = () => photo.InputStream
            };
//then I save to Azure

比如说我想将照片的InputStream转换成100x100像素大小,该怎么做呢?


你目前尝试了什么?在网上有大量关于使用C#调整图像大小的教程。 - user47589
我已经能够使用WebImage更改图像大小,但是现在我只有一个WebImage对象的图像,我无法使用Data=() => WebImageObject保存它。这种方法不起作用。 - Jynn
1个回答

13

这是我的做法:

byte[] imageBytes; 

//Of course image bytes is set to the bytearray of your image      

using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        using (Image img = Image.FromStream(ms))
        {
            int h = 100;
            int w = 100;

            using (Bitmap b = new Bitmap(img, new Size(w,h)))
            {
                using (MemoryStream ms2 = new MemoryStream())
                {
                    b.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
                    imageBytes = ms2.ToArray();
                }
            }
        }                        
    }    

接下来,我使用MemoryStream进行上传。我使用 Blob 存储,并使用 UploadFromStreamAsync 将其加载到 Blob 中。

这是它的基本视图。


有没有一种方法可以在不将图像保存到磁盘的情况下转换图像格式?比如在内存流中更改格式,然后保存到数据库。 - sairfan
@sairfan 我写这个已经有一段时间了,但是看代码,似乎保存到的是 ms2 对象,它是一个 MemoryStream。我没有测试过将其转换为其他 ImageFormat,但我想你可以将格式更改为此处找到的另一个支持的 ImageFormat:https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imaging.imageformat?view=dotnet-plat-ext-6.0 - Rogala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接