如何简化此 MemoryStream 代码
此代码返回从字节数组加载的图像的缩略图。我试图理解为什么作者使用 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);
}
}
}
}
}
This code returns a thumbnail of an image loaded from a byte array. I'm trying to understand why the author is using 4 memory streams and if there is a simple way of rewriting this or if it is okay the way it is.
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);
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
他实际上在这里只使用了 3 个 MemoryStream,但他只需要使用 2 个(我认为)。您应该能够将此代码替换
为
:我认为他创建了第三个 MemoryStream 因为
ms
MemoryStream 不在开头。He's actually only using 3 MemoryStreams here, but he needs to only use 2 (I think). You should be able to replace this code:
with this:
I think he created the third MemoryStream because the
ms
MemoryStream wasn't at the beginning.我认为这是正确的
i think this will be right
我认为之前的答案缺少作者强制转换为 jpeg。
I think the previous answers are missing that the author is forcing a conversion to jpeg.
我认为最后一个,
m
,可以被消除。只需重置ms.Position=0
就足够了。请注意,主要的节省将消除ms.ToArray()
。其他 MemoryStream 看起来是必要的,或者至少消除或重新使用它们没有什么好处。
I would think the last one,
m
, can be eliminated. Simply resettingms.Position=0
would be enough. Note that the main savings would to eliminate thems.ToArray()
.The other MemoryStreams look necessary, or at least there is little to be gained by eliminating or re-using them.