如何将图像对象转换为流 [英] how to convert an image object to stream
问题描述
Hye Everyone,
我在Windows Mobile 7工作,
我需要转换从相机中提取的图像流capturetask,
到字符串中将其保存在我的数据库中....
Hye Everyone,
I m working in Windows Mobile 7,
and i need to convert the image stream otained from the camera capturetask,
into string to save it in my database....
void photoChooser_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null)
{
//Convert e.ChosenPhoto to string
}
}
我该怎么做。
i试过 -
how can i do this.
i have tried -
private byte[] imageByte = new Byte[e.ChosenPhoto.Length];
string imgStream = e.ChosenPhoto.Read(imageByte, 0, imageByte.Length);
但没有结果。
如何将流转换为字符串并返回流。
提前感谢
but no result.
how can i convert stream to string and back to stream.
thanks in advance
推荐答案
不要将它转换为字符串 - 将其转换为字节数组。字符串有一个默认的转换,你不需要图像数据,字节不是。大多数数据库都有一个VarBinary和一个VerChar,用于保存这些数据。
然后将图像转换为字节:
Don''t convert it to a string - convert it to a byte array. Strings have a default conversion which you do not want for image data, bytes don''t. Most databases have a VarBinary as well as a VerChar which is designed to hold such data.
Then convert the image to bytes:
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
如果您的框架不包含ImageConverter类(我不知道它是否存在),您可以通过将图像写入流来转换它,然后使用Stream.ToArray方法,但效率相当低。
我试过这个,但它给了一个例外
ConvertTo没有在Base Type转换器中实现。
什么我应该这样做。
以及
如何将这个字节数组转换回图像。
这可能意味着它没有在您的框架中实现 - 并非所有内容都在移动框架中。你可以通过更混乱的流:
If your framework doesn''t the include ImageConverter class (and I don''t know if it does) you can convert it by writing the image to a stream, and then using the Stream.ToArray method but that is quite a bit less efficient.
"i tried this, but it is giving an exception
ConvertTo not implemented in base TypeConverter.
what should i do.
and also,
how can i convert this byte array back to image."
That probably means it isn''t implemented in your framework - not everything is in the mobile frameworks. You can go via the messier stream though:
public static byte[] ImageToByteStream(Image img)
{ byte[] data = new byte[0];
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Seek(0,0);
data = ms.ToArray();
}
return data;
}
最好使用Bitmap.FromStream方法反转过程返回图像。
It is probably best if you reverse the process to go back to an image using the Bitmap.FromStream method.
大家好,
您可以将Image对象转换为流:
Hi everyone,
You can convert an Image object to a stream as:
private Stream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400,400);
wb.Render(image1, new TranslateTransform {X=400, Y=400});
wb.Invalidate();
Stream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
干杯
Cheers
这篇关于如何将图像对象转换为流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!