[英]How to convert ImageCodecInfo to byte[] or Stream
I want to upload an optimized images to Amazon. 我想将优化的图像上传到亚马逊。
So that I have found this article that explains how to optimize an image with a compression level. 因此,我找到了这篇文章 ,解释了如何优化具有压缩级别的图像。
The problem is that this example saves the image to disk and I need to save it to Amazon storage. 问题在于该示例将图像保存到磁盘,而我需要将其保存到Amazon存储。
I have this code: 我有以下代码:
public static ImageCodecInfo OptimizeImage(Image image, string fileName, long compression, string type)
{
var encoderParams = new EncoderParameters(1)
{
Param = {[0] = new EncoderParameter(Encoder.Quality, compression)}
};
return GetEncoderInfo(type);
}
private static ImageCodecInfo GetEncoderInfo(string mime_type)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int i = 0; i <= encoders.Length; i++)
{
if (encoders[i].MimeType == mime_type)
return encoders[i];
}
return null;
}
I should have a Stream
or byte[]
object in order to send it to the UploadImageToAmazon
method as parameter. 我应该有一个Stream
或byte[]
对象,以便将其作为参数发送到UploadImageToAmazon
方法。
So, I have an Image object and its ImageCodecInfo, how can I convert it to Stream
or to byte[]
? 因此,我有一个Image对象及其ImageCodecInfo,如何将其转换为Stream
或byte[]
?
Or if you could suggest me how to optimize images and upload them into amazon would be also good. 或者,如果您可以建议我如何优化图像并将其上传到亚马逊,那也很好。
Thanks. 谢谢。
You can save an Image object to a Stream with Image.Save Method (Stream, ImageFormat) 您可以使用Image.Save方法将Image对象保存到Stream中(Stream,ImageFormat)
Edit : 编辑:
If I recap with the code provided in the example you linked: 如果我回顾一下您链接的示例中提供的代码:
private void SaveJpg(Image image, string file_name, long compression)
{
try
{
EncoderParameters encoder_params = new EncoderParameters(1);
encoder_params.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Quality, compression);
ImageCodecInfo image_codec_info =
GetEncoderInfo("image/jpeg");
File.Delete(file_name);
using(var imageStream = new Stream()){
// save to stream
image.Save(imageStream, image_codec_info, encoder_params);
// upload
UploadImageToAmazon(imageStream);
}
}
catch (Exception ex)
{
MessageBox.Show("Error saving file '" + file_name +
"'\nTry a different file name.\n" + ex.Message,
"Save Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.