silverlight 生成缩略图

先写个cs文件

View Code
using System;
using System.Net;
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.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Media.Imaging;

namespace CloudOrder
{
    public class FileUpload
    {
        OpenFileDialog dlg = new OpenFileDialog();
        bool? result;
        public string oldname = "";
        public string name = "";
        public void ImageUpload()
        {
            dlg.Multiselect = false;
            //dlg.Filter = "JPG 图片 (*.jpg)|*.jpg|PNG 图片 (*.png)|*.png";
            //dlg.Filter = " 图片 (*.jpg;*.jpeg;*.png;*.gif)|*.jpg;*.jpeg;*.png;*.gif|所有文件 (*.*)|*.*";
            dlg.Filter = " 图像文件 (*.jpg;*.jpeg;*.png;*.gif;*.bmp)|*.jpg;*.jpeg;*.png;*.gif;*.bmp";
            result = dlg.ShowDialog();
            try
            {
                oldname = dlg.File.Name;
                name = dlg.File.Name;
            }
            catch { oldname = ""; }
        }
        public void StartUpload(string uploadedName, bool IsNeedBigPic)
        {
            if (result != null && result == true)
            {
                //string name = dlg.File.Name;
                //string extension = name.Substring(name.LastIndexOf('.'), name.Length - name.LastIndexOf('.')); //取得扩展名(包括“.”) 
                //string uploadedName = DateTime.Now.ToString("yyyyMMddHHmmss") + extension; // 根据当前时间重命名 
                //uploadImage(uploadedName, dlg.File.OpenRead());
                //textBox1.Text = string.Format("上传成功!已重命名为:{0}", uploadedName);
                //保存缩略图
                BitmapImage bmap = GetImageSource() as BitmapImage;
                WriteableBitmap wimg = this.RenderThumbnail(bmap, Helper.KDJS * 3, Helper.GDJS * 3);
                MemoryStream ms = new MemoryStream(BitMapToByte(wimg));
                uploadImage(uploadedName, ms);
                if (IsNeedBigPic == true)
                {
                    //保存原图
                    string uploadedName2 = "x_" + uploadedName;
                    uploadImage(uploadedName2, dlg.File.OpenRead());
                }
            }
        }
        public ImageSource GetImageSource()
        {
            BitmapImage bitmap = new BitmapImage();
            try
            {
                FileStream fileStream = dlg.File.OpenRead();
                name = dlg.File.Name;
                long picLength = fileStream.Length;
                byte[] m_imageBuffer = new byte[picLength];
                fileStream.Read(m_imageBuffer, 0, (int)picLength);    // 读取图片 二进制 
                bitmap.SetSource(fileStream);
            }
            catch { }
            return bitmap;
        }
        private void uploadImage(string fileName, Stream data)
        {
            Uri uri = new Uri(string.Format("/DataHandler.ashx?filename={0}", fileName), UriKind.Relative);

            WebClient client = new WebClient();
            client.OpenWriteCompleted += delegate(object s, OpenWriteCompletedEventArgs e)
            {
                uploadData(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            client.OpenWriteAsync(uri);
        }
        private void uploadData(Stream input, Stream output)
        {
            byte[] buffer = new byte[4096];
            int bytes;

            while ((bytes = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytes);
            }
        }


        #region 生成缩略图
        /// <summary>
        /// 生成縮略圖
        /// </summary>
        /// <param name="bitmap">要轉換的位圖</param>
        /// <returns>返回WriteableBitmap</returns>
        public WriteableBitmap RenderThumbnail(BitmapImage bitmap, double width, double height)
        {
            Image img = new Image();
            img.Width = width;
            img.Height = height;
            img.Source = bitmap;
            WriteableBitmap Wimg = new WriteableBitmap(img, null);
            Wimg.Invalidate();
            return Wimg;
        }

        #region 转化为Byte数组
        public byte[] BitMapToByte(System.Windows.Media.Imaging.WriteableBitmap bitmap)
        {
            if (bitmap == null) return null;
            int width = bitmap.PixelWidth;
            int height = bitmap.PixelHeight;
            int bands = 3;
            byte[][,] raster = new byte[bands][,];

            for (int i = 0; i < bands; i++)
            {
                raster[i] = new byte[width, height];
            }

            for (int row = 0; row < height; row++)
            {
                for (int column = 0; column < width; column++)
                {
                    int pixel = bitmap.Pixels[width * row + column];
                    byte a = ((byte)(pixel >> 24));

                    byte r = (byte)(pixel >> 16);//4 R
                    byte g = (byte)(pixel >> 8);//2 G
                    byte b = (byte)pixel;//0 B

                    if (a < 2)
                    {
                        raster[0][column, row] = (byte)(255 - r);
                        raster[1][column, row] = (byte)(255 - g);
                        raster[2][column, row] = (byte)(255 - b);
                    }
                    else
                    {
                        raster[0][column, row] = (byte)(r * 255.0 / a);
                        raster[1][column, row] = (byte)(g * 255.0 / a);
                        raster[2][column, row] = (byte)(b * 255.0 / a);
                    }
                }
            }

            FluxJpeg.Core.ColorModel model = new FluxJpeg.Core.ColorModel { colorspace = FluxJpeg.Core.ColorSpace.RGB };
            FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);


            //Encode the Image as a JPEG
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            FluxJpeg.Core.Encoder.JpegEncoder encoder = new FluxJpeg.Core.Encoder.JpegEncoder(img, 100, stream);
            encoder.Encode();

            //Back to the start
            stream.Seek(0, System.IO.SeekOrigin.Begin);

            //Get teh Bytes and write them to the stream
            byte[] binaryData = new byte[stream.Length];
            long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);
            return binaryData;
        }
        #endregion
        #endregion

    }
}

选择图片按钮事件

View Code
        #region 图片上传按钮
        //图片上传
        FileUpload image1 = new FileUpload();
        private void btUpload_Click(object sender, RoutedEventArgs e)
        {
            image1.ImageUpload();
            if (image1.name != "")
                img.Source = image1.GetImageSource();
        }
        #endregion

确定上传按钮事件

View Code
if (img.Source != oldimg && image1.name != "")
                    {
                        ImgUrl = DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
                        BigImgUrl = "x_" + ImgUrl;
                        image1.StartUpload(pdto.ImgUrl, true);//true表示保存原图(平板大图显示用),false表示只压缩保存
                    }

//oldimg(原图名称)和image1.name只为判断图片是否被更改了,若没更改不更新,无他用

posted @ 2013-01-28 17:27  royin  阅读(382)  评论(0编辑  收藏  举报