我在创建缩略图然后将它们转换为字节数组方面花了很多时间。我已经尝试了三种方法,并且所有 3 次都出现错误。
第一个是使用Bitmap.GetThumbnailImage,我以前用过,然后直接保存到Response.OutputStream
第二个是使用带有 DrawImage() 的 System.Drawing.Graphics。还是不行。
第三个只是创建一个新的位图,传入旧的位图,并设置新的大小。同样的错误。
值不能为空。
参数名称:encoder
描述:当前web请求执行过程中出现未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.ArgumentNullException:值不能为空。
参数名称:编码器
源错误:
在执行当前网络请求的过程中产生了一个未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常起源和位置的信息。
堆栈跟踪:
[ArgumentNullException:值不能为空。
参数名称:编码器]
System.Drawing.Image.Save(Stream 流,ImageCodecInfo 编码器,EncoderParameters encoderParams) +615244
这是我的方法的代码。也许有人会看到我做错了什么。如果您不确定 GetThumbSize,它只是一种获取图像大小和最大拇指大小然后计算实际大小以保持纵横比的方法。
public static System.Drawing.Image.GetThumbnailImageAbort thumbnailCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
public static bool ThumbnailCallback()
{
return false;
}
/// <summary>
///
/// </summary>
/// <param name="image"></param>
/// <param name="size"></param>
/// <remarks>
/// This method will throw a AccessViolationException when the machine OS running the server code is windows 7.
/// </remarks>
/// <returns></returns>
public static byte[] CreateThumbnail(byte[] imageData, Size size)
{
using (MemoryStream inStream = new MemoryStream())
{
inStream.Write(imageData, 0, imageData.Length);
using (System.Drawing.Image image = Bitmap.FromStream(inStream))
{
Size thumbSize = GetThumbSize(new Size(image.Width, image.Height), size);
//do not make image bigger
if (thumbSize.Equals(image.Size) || (image.Width < size.Width || image.Height < size.Height))
{
//if no shrinking is ocurring, return the original bytes
return imageData;
}
else
{
using (System.Drawing.Image thumb = image.GetThumbnailImage(thumbSize.Width, thumbSize.Height, thumbnailCallback, IntPtr.Zero))
{
using (MemoryStream outStream = new MemoryStream())
{
thumb.Save(outStream, thumb.RawFormat);
return outStream.ToArray();
}
}
}
}
}
}
此行抛出错误:
thumb.Save(outStream, thumb.RawFormat);
有任何想法吗?谢谢您的帮助!