将图像大小调整为字节数组

时间:2013-02-20 16:35:41

标签: c# file-upload bytearray image-resizing

我目前正在尝试将图片调整为缩略图,以便在完成上传时显示为预览。我正在使用fineuploader插件来上传图像的一部分。我一直不断得到“参数无效”。我见过许多与此相关的帖子,并尝试了大部分解决方案,但没有成功。以下是代码片段:

    public static byte[] CreateThumbnail(byte[] PassedImage, int LargestSide)  
    {  
        byte[] ReturnedThumbnail = null;  

        using (MemoryStream StartMemoryStream = new MemoryStream(),  
                            NewMemoryStream = new MemoryStream())  
        {  
            StartMemoryStream.Write(PassedImage, 0, PassedImage.Length); //error being fire in this line 

            System.Drawing.Bitmap startBitmap = new Bitmap(StartMemoryStream);  

            int newHeight;  
            int newWidth;  
            double HW_ratio;  
            if (startBitmap.Height > startBitmap.Width)  
            {  
                newHeight = LargestSide;  
                HW_ratio = (double)((double)LargestSide / (double)startBitmap.Height);  
                newWidth = (int)(HW_ratio * (double)startBitmap.Width);  
            }  
            else 
            {  
                newWidth = LargestSide;  
                HW_ratio = (double)((double)LargestSide / (double)startBitmap.Width);  
                newHeight = (int)(HW_ratio * (double)startBitmap.Height);  
            }  

            System.Drawing.Bitmap newBitmap = new Bitmap(newWidth, newHeight);  

            newBitmap = ResizeImage(startBitmap, newWidth, newHeight);  

            newBitmap.Save(NewMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);  

            ReturnedThumbnail = NewMemoryStream.ToArray(); 
        }  

        return ReturnedThumbnail;  
    }  

我没有想法,感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您的错误位于new Bitmap(startMemoryStream)行,而不是上面的行。

documentation表示在以下情况下可能发生此异常:

  

stream不包含图像数据或为null。

     

-OR -

     

stream包含一个PNG图像文件,其单个维度大于65,535像素。

您应该检查那里是否有有效的PNG文件。例如,将其写入文件并尝试在图像查看器中打开它。

答案 1 :(得分:-1)

该代码很危险 - System.Drawing类的每个实例都必须放在using(){}子句中。

这是一个使用ImageResizer NuGet包的替代解决方案,可以安全地调整图像大小。

var ms = new MemoryStream();
ImageResizer.Current.Build(PassedImage, ms, new ResizeSettings(){MaxWidth=LargestSide, MaxHeight=LargestSide});
return ImageResizer.ExtensionMethods.StreamExtensions.CopyToBytes(ms);
相关问题