我在创建缩略图然后将它们转换为字节数组方面遇到了很大的麻烦。我尝试了三种方法,3次都出错了。
第一个是使用 Bitmap.GetThumbnailImage,我过去使用过它,然后直接保存到 Response.OutputStream 中
第二个是将 System.Drawing.Graphics 与 DrawImage() 一起使用。还是不行。
第三种只是创建一个新的位图,传入旧的位图,并设置新的大小。同样的错误。
值不能为空。
参数名称:编码器
描述:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。
异常详细信息:System.ArgumentNullException:值不能为 null。
参数名称:编码器
来源错误:
执行当前 Web 请求期间生成未处理的异常。有关异常来源和位置的信息可以使用下面的异常堆栈跟踪来识别。
堆栈跟踪:
[ArgumentNullException:值不能为空。
参数名称:编码器]
System.Drawing.Image.Save(流流,ImageCodecInfo编码器,EncoderParameters编码器参数)+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);
有任何想法吗?谢谢您的帮助!