我正在尝试将位图图像转换为字节数组。我使用MediaLibrary类选择了所有图像,并将其添加到位图图像列表中。以下是我的代码:
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
for (int i = 0; i < imgname.Count(); i++)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(@"ImagesZipFolder\" + imgname[i], System.IO.FileMode.CreateNew, store))
{
byte[] bytes = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wBitmap = new WriteableBitmap(ImgCollection[i]);
wBitmap.SaveJpeg(ms, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
bytes = ms.GetBuffer();
stream.Write(bytes, 0, bytes.Length);
}
// byte[] bytes = Encoding.UTF8.GetBytes(imgname[i]);//new byte[ImgCollection[i].PixelWidth * ImgCollection[i].PixelHeight * 4];
// stream.Write(bytes, 0, bytes.Length);
}
}
}
else {
directory = true;
}
}
我想做的事情是从设备中选择所有图像或照片,并创建一个zip文件。我已经成功地创建了一个图像的zip文件。但是当我打开zip文件并双击图像时,有些图像无法显示。我认为问题出在读取图像字节上。我不知道哪里出错了?我的代码有问题吗?
ms.ToArray()
而不是ms.GetBuffer()
吗? - Kevin Gossems.CopyTo(stream);
即可。这不会解决您的问题,但它会使您的代码更易于阅读并节省一些 RAM。而且,seek 操作应该在 ms 上调用,而不是在 stream 上调用。 - Kevin Gosse