windows phone开发中图片和二进制相互转换

引用using System.Windows.Media.Imaging;

using System;
using System.Net;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Commons
{
    /// <summary>
    
/// 类型转换集合
    
/// </summary>
    public class TypeConverter
    {
        /// <summary>
        
/// 把图片转化成二进制
        
/// </summary>
        
/// <param name="sourceImage"></param>
        
/// <returns></returns>
        public static byte[] ImageToByteArray(Image sourceImage)
        {
            BitmapSource bs = sourceImage.Source as BitmapSource;
            using (MemoryStream ms = new MemoryStream())
            {
                System.Windows.Media.Imaging.WriteableBitmap writeableBitmap = new WriteableBitmap(bs);
                System.Windows.Media.Imaging.Extensions.SaveJpeg(writeableBitmap, ms, bs.PixelWidth, bs.PixelHeight, 0100);
                return ms.GetBuffer();
            }
        }

        /// <summary>
        
/// 把二进制转化为Image图片
        
/// </summary>
        
/// <param name="bits"></param>
        
/// <returns></returns>
        public static Image ByteArrayToImage(byte[] bits)
        {
            BitmapImage bitmapImage = new BitmapImage();
            using (MemoryStream ms = new MemoryStream(bits))
            {
                bitmapImage.CreateOptions = BitmapCreateOptions.DelayCreation;
                bitmapImage.SetSource(ms);
                Image image = new Image();
                image.Source = bitmapImage;
                return image;
            }
        }
    }
}

posted on 2011-10-17 16:53  Kingly  阅读(457)  评论(0编辑  收藏  举报