如何将图像转换为字节数组? [英] How to convert image to byte array?
本文介绍了如何将图像转换为字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为windows phone app工作,如何将图像转换为字节数组?因为我必须保存在SqlLite数据库中。我试过下面的代码,但在'
I working for windows phone app, How to convert image to byte array? as i have to save in SqlLite datatabse. I tried below code, but gives error at '
WriteableBitmap
'时出错 - 指针无效。
' - Invalid pointer.
public byte[] ImageToArray()
{
BitmapImage image = new BitmapImage();
image.CreateOptions = BitmapCreateOptions.None;
image.UriSource = new Uri(image1.Source.ToString(), UriKind.Relative);
WriteableBitmap wbmp = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wbmp.SaveJpeg(ms, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
return ms.ToArray();
}
推荐答案
我还没有测试过,但这应该可以解决问题:
I haven't tested it, but this should do the trick:
public Byte[] BufferFromImage(this BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}
这是一种扩展方法。你可以将它放在它自己的类中并像这样使用它:
This is an extention method. You would put this in it's own class and use it like this:
BitmapImage myImage = new BitmapImage();
...
byte[] imageBytes = myImage.ToByteArray();
转换为base64
convert to base64
using (FileStream stream = new FileStream(indexFile.Path, FileMode.Open, FileAccess.Read))
{
byte[] objByte = new byte[stream.length];
string base64 = base64 = Convert.ToBase64String(objByte);
}
File.ReadAllBytes(字符串路径)
File.ReadAllBytes( string path)
这篇关于如何将图像转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文