此代码返回从字节数组加载的图像的缩略图。我试图理解为什么作者使用4个内存流,如果有一种简单的方法可以重写它,或者它是否正常。
public Image GetThumbnail(int height, int width)
{
//load the image from a byte array (imageData)
using (MemoryStream mem = new MemoryStream(this.imageData))
{
// Create a Thumbnail from the image
using (Image thumbPhoto = Image.FromStream(mem,
true).GetThumbnailImage(height, width, null,
new System.IntPtr()))
{
// Convert the Image object to a byte array
using (MemoryStream ms = new MemoryStream())
{
thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
using (MemoryStream m = new MemoryStream(ms.ToArray()))
{
return Image.FromStream(m, true);
}
}
}
}
}
答案 0 :(得分:3)
他实际上只在这里使用3个MemoryStreams,但他只需要使用2个(我认为)。您应该能够替换此代码:
using (MemoryStream m = new MemoryStream(ms.ToArray()))
{
return Image.FromStream(m, true);
}
用这个:
ms.Seek(0, SeekOrigin.Begin);
return Image.FromStream(ms, true);
我认为他创建了第三个MemoryStream,因为ms
MemoryStream不在开头。
答案 1 :(得分:1)
public Image GetThumbnail(int height, int width) { //load the image from a byte array (imageData) using (MemoryStream mem = new MemoryStream(this.imageData)) { // Create a Thumbnail from the image using (Image thumbPhoto = Image.FromStream(mem, true).GetThumbnailImage(height, width, null, new System.IntPtr())) { return thumbPhoto; } } }
我认为这是对的
答案 2 :(得分:1)
我认为以前的答案缺少作者正在强制转换为jpeg。
答案 3 :(得分:1)
我认为可以消除最后一个m
。只需重置ms.Position=0
即可。请注意,主要的节省将消除ms.ToArray()
。
其他MemoryStream看起来是必要的,或者至少通过消除或重新使用它们几乎无法获得。