windows store app C#读写图像的完整代码

using System;
using System.Threading.Tasks;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Graphics.Imaging;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using System.IO;
using Windows.Foundation;
using System.Collections.Generic;

namespace Common
{
    public class ImageHelper
    {
        public const int THumbLength = 400;
        public  static Size MinSizeSupported = new Size(200, 200);
        public static Size MaxSizeSupported = new Size(4000, 3000);

        static Guid EncoderIDFromFileExtension(string strExtension)
        {
            Guid encoderId;
            switch (strExtension.ToLower())
            {
                case ".jpg":
                case ".jpeg":
                    encoderId = BitmapEncoder.JpegEncoderId;
                    break;
                case ".bmp":
                    encoderId = BitmapEncoder.BmpEncoderId;
                    break;
                case ".png":
                default:
                    encoderId = BitmapEncoder.PngEncoderId;
                    break;
            }
            return encoderId;
        }
        static Guid DecoderIDFromFileExtension(string strExtension)
        {
            Guid encoderId;
            switch (strExtension.ToLower())
            {
                case ".jpg":
                case ".jpeg":
                    encoderId = BitmapDecoder.JpegDecoderId;
                    break;
                case ".bmp":
                    encoderId = BitmapDecoder.BmpDecoderId;
                    break;
                case ".png":
                default:
                    encoderId = BitmapDecoder.PngDecoderId;
                    break;
            }
            return encoderId;
        }

        public async static Task<WriteableBitmap> ReadBitmap(IRandomAccessStream fileStream, string type)
        {
            WriteableBitmap bitmap = null;
            try
            {
                Guid decoderId = DecoderIDFromFileExtension(type);

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(decoderId, fileStream);
                BitmapTransform tf = new BitmapTransform();

                uint width = decoder.OrientedPixelWidth;
                uint height = decoder.OrientedPixelHeight;
                double dScale = 1;

                if (decoder.OrientedPixelWidth > MaxSizeSupported.Width || decoder.OrientedPixelHeight > MaxSizeSupported.Height)
                {
                    dScale = Math.Min(MaxSizeSupported.Width / decoder.OrientedPixelWidth, MaxSizeSupported.Height/decoder.OrientedPixelHeight );
                    width =(uint)( decoder.OrientedPixelWidth * dScale);
                    height = (uint)(decoder.OrientedPixelHeight * dScale);

                    tf.ScaledWidth = (uint)(decoder.PixelWidth* dScale); 
                    tf.ScaledHeight = (uint)(decoder.PixelHeight* dScale); 
                }

               
                bitmap = new WriteableBitmap((int)width, (int)height);
                
                

                PixelDataProvider dataprovider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, tf,
                    ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
                byte[] pixels = dataprovider.DetachPixelData();

                Stream pixelStream2 = bitmap.PixelBuffer.AsStream();

                pixelStream2.Write(pixels, 0, pixels.Length);
                //bitmap.SetSource(fileStream);
            }
            catch
            {
            }

            return bitmap;
        }

        public async static Task<WriteableBitmap> ReadBitmap(StorageFile file)
        {
            IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
            WriteableBitmap bitmap = await ReadBitmap(stream, file.FileType.ToLower());

            return bitmap;
        }


        public async static Task<bool> SaveBitmap(IRandomAccessStream stream, Guid encoderId, WriteableBitmap bitmap, BitmapTransform bitmapTransform)
        {
            bool bSuccess = true;
            try
            {
                Stream pixelStream = bitmap.PixelBuffer.AsStream();

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
                if (bitmapTransform != null)
                {
                    encoder.BitmapTransform.ScaledWidth = bitmapTransform.ScaledWidth;
                    encoder.BitmapTransform.ScaledHeight = bitmapTransform.ScaledHeight;
                    encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
                    encoder.BitmapTransform.Bounds = bitmapTransform.Bounds;
                }

                byte[] pixels = new byte[pixelStream.Length];

                pixelStream.Read(pixels, 0, pixels.Length);

                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    (uint)bitmap.PixelWidth,
                    (uint)bitmap.PixelHeight,
                    96, // Horizontal DPI
                    96, // Vertical DPI
                    pixels
                );
                await encoder.FlushAsync();
               
                pixelStream.Dispose();
            }
            catch
            {
                bSuccess = false;
            }

            return bSuccess;
        }

         async static Task<bool> SaveBitmap(StorageFile file, WriteableBitmap bitmap, BitmapTransform bitmapTransform)
        {
            bool bSuccess = true;
            try
            {
                // Application now has read/write access to the saved file
                Guid encoderId = EncoderIDFromFileExtension(file.FileType);

                
                IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                bSuccess = await SaveBitmap(fileStream, encoderId,bitmap,bitmapTransform);

                fileStream.Dispose();
              
            }
            catch
            {
                bSuccess = false;
            }

            return bSuccess;
        }

        public async static Task<bool> SaveBitmap(StorageFile file, WriteableBitmap bitmap)
        {
            bool bSuccess = await SaveBitmap(file, bitmap, null);
            return bSuccess;
        }

        public async static Task<bool> SaveBitmapWithFilePicker(WriteableBitmap bitmap)
        {
            FileSavePicker save = new FileSavePicker();
            save.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            save.DefaultFileExtension = ".jpg";
            save.SuggestedFileName = "new image";
            save.FileTypeChoices.Add(".bmp", new List<string>() { ".bmp" });
            save.FileTypeChoices.Add(".png", new List<string>() { ".png" });
            save.FileTypeChoices.Add(".jpg", new List<string>() { ".jpg", ".jpeg" });

            StorageFile savedItem = await save.PickSaveFileAsync();
            if (savedItem == null)
            {
                return false;
            }

            return await SaveBitmap(savedItem, bitmap);
        }

        public async static Task<bool> SaveBitmapAsThumb(StorageFile file, WriteableBitmap bitmap, double width, double height)
        {
            BitmapTransform transform = new BitmapTransform();

            double ratio = Math.Min(width / bitmap.PixelWidth, height / bitmap.PixelHeight);

            transform.ScaledWidth = (uint)(bitmap.PixelWidth * ratio);
            transform.ScaledHeight = (uint)(bitmap.PixelHeight * ratio);
            transform.InterpolationMode = BitmapInterpolationMode.Fant;

            return await SaveBitmap(file, bitmap, transform);
        }
        public async static Task<bool> SaveBitmapAsThumb(StorageFile file, WriteableBitmap bitmap,  Windows.Foundation.Rect cropRect)
        {
            BitmapTransform transform = new BitmapTransform();


            double ratio =THumbLength/ Math.Max(cropRect.Width, cropRect.Height );

            transform.ScaledWidth = (uint)(bitmap.PixelWidth * ratio);
            transform.ScaledHeight = (uint)(bitmap.PixelHeight * ratio);
            transform.Bounds = new BitmapBounds()
            {
                X = (uint)(cropRect.X * ratio),
                Y = (uint)(cropRect.Y * ratio),
                Width = (uint)(cropRect.Width * ratio),
                Height = (uint)(cropRect.Height * ratio)
            };
            transform.InterpolationMode = BitmapInterpolationMode.Fant;

            return await SaveBitmap(file, bitmap, transform);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值