日期:2014-05-17 浏览次数:20861 次
windowsphone7和siverlight中的BitmapImage和Image提供的接口还是很比较大的区别的,总体来说siverlight的封装性更加健全一些。
同时在压缩bitmap的时候,siverlight会提供设置和访问图像dpi(dots per inch)和pixel的函数,但是wp7中只能访问和操作pixel。这样的话在wp7下,对于压缩一张图片来说,你可以很方便增加或减少像素,但是却很难访问它的dpi,那么图片的实际宽度和高度就很难定制了。
下面是对图片和文件流格式的一个转换类,可以参考一下:
public class ImageUtil { /// <summary> /// 将Image转换成二进制流 /// </summary> /// <param name="sourceImage"></param> /// <returns></returns> public static byte[] ImageToByteArray(Image sourceImage) { return ImageSourceToByteArray(sourceImage.Source); } /// <summary> /// 将ImageSource转换成二进制流 /// </summary> /// <param name="sourceImage"></param> /// <returns></returns> public static byte[] ImageSourceToByteArray(ImageSource source) { BitmapSource bs = (BitmapSource)source; using (MemoryStream ms = new MemoryStream()) { WriteableBitmap writeableBitmap = new WriteableBitmap(bs); Extensions.SaveJpeg(writeableBitmap, ms, bs.PixelWidth, bs.PixelHeight, 0, 100); return ms.GetBuffer(); } } /// <summary> /// 将二进制流转换为Image格式图片 /// </summary> /// <param name="bitData"></param> /// <returns></returns> public static Image ByteArrayToImage(byte[] bitData) { Image image = new Image(); image.Source = ByteArrayToBitmapImage(bitData); return image; } /// <summary> /// 将二进制流转换为BitmapImage格式图片 /// </summary> /// <param name="bitData"></param> /// <returns></returns> public static BitmapImage ByteArrayToBitmapImage(byte[] bitData) { BitmapImage bitmap = new BitmapImage(); using (MemoryStream ms = new MemoryStream(bitData)) { bitmap.CreateOptions = BitmapCreateOptions.DelayCreation; bitmap.SetSource(ms); return bitmap; } } /// <summary> /// 将流数据写入jpeg文件 /// </summary> /// <param name="stream"></param> /// <param name="fileDirectory"></param> /// <param name="filename"></param> /// <param name="targetWidth"></param> /// <param name="targetHeight"></param> public static void WriteStreamObjectToJPEG(Stream stream, string fileDirectory,string filename, int targetWidth, int targetHeight) { using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { if (!store.DirectoryExists(fileDirectory)) { store.CreateDirectory(fileDirectory); } WriteableBitmap bmpImage = new WriteableBitmap(targetWidth, targetHeight); bmpImage.SetSource(stream); using (IsolatedStorageFileStream isoStream = store.OpenFile(fileDirectory + '/' + filename, FileMode.OpenOrCreate)) { System.Windows.Media.Imaging.Extensions.SaveJpeg(bmpImage, isoStream, targetWidth, targetHeight, 0, 100); } } } /// <summary> /// 将jpeg文件写入到数据流中 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static BitmapImage ReadBitmapImageFromJPEG(string filePath) { BitmapImage image =