• Metro style app 图片Scale ,Crop. 图片的打开,保存


    Metro style app

    一.图片Scale ,Crop操作

        public class PhotoEdit
        {
            public async static Task<WriteableBitmap> ScaleAndCorpPhoto(IStorageFile file)
            {
                if (file == null) return null;
                // create a stream from the file and decode the image
                var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
                BitmapTransform transform = new BitmapTransform();
                BitmapBounds bounds = new BitmapBounds();
                transform.ScaledWidth = 500;
                transform.ScaledHeight = 500;
                const int croppedHeight = 400;
                const int croppedWidth = 400;
                bounds.Height = croppedHeight;
                bounds.Width = croppedWidth;
                bounds.X = 0;
                bounds.Y = 0;
                transform.Bounds = bounds;
    
                // Get the pixels in Bgra8 to match what the WriteableBitmap will expect
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);
                byte[] pixels = pixelData.DetachPixelData();
    
                // And stream them into a WriteableBitmap 
                WriteableBitmap cropBmp = new WriteableBitmap(croppedHeight, croppedWidth);
                Stream pixStream = cropBmp.PixelBuffer.AsStream();
                pixStream.Write(pixels, 0, pixels.Length);
                return cropBmp; 
            }
        }
    

     调用方法

            private async System.Threading.Tasks.Task ScaleAndCorpPhoto()
            { 
                FileOpenPicker fileOpenPicker = new FileOpenPicker();
                fileOpenPicker.CommitButtonText = "打开";
                fileOpenPicker.FileTypeFilter.Insert(0, ".jpg");
                StorageFile file = await fileOpenPicker.PickSingleFileAsync();
                if (file == null) return;
                image.Source = await PhotoEdit.ScaleAndCorpPhoto(file);
            }
    

     二、图片的打开与保存

    1.图片的打开. 选择要显示的图片,最后将图片显示在Image控件中.

           private static BitmapImage srcImage = new BitmapImage();
            private static WriteableBitmap wbsrcImage;
            public async static void OpenImage(Image ImageOne)
            {
                FileOpenPicker imagePicker = new FileOpenPicker
                {
                    ViewMode = PickerViewMode.Thumbnail,
                    SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                    FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" }
                };
    
                Guid decoderId;
                StorageFile imageFile = await imagePicker.PickSingleFileAsync();
                if (imageFile != null)
                {
                    srcImage = new BitmapImage();
                    using (IRandomAccessStream stream = await imageFile.OpenAsync(FileAccessMode.Read))
                    {
                        srcImage.SetSource(stream);
                        switch (imageFile.FileType.ToLower())
                        {
                            case ".jpg":
                            case ".jpeg":
                                decoderId = Windows.Graphics.Imaging.BitmapDecoder.JpegDecoderId;
                                break;
                            case ".bmp":
                                decoderId = Windows.Graphics.Imaging.BitmapDecoder.BmpDecoderId;
                                break;
                            case ".png":
                                decoderId = Windows.Graphics.Imaging.BitmapDecoder.PngDecoderId;
                                break;
                            default:
                                return;
    
                        }
                        Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(decoderId, stream);
                        int width = (int)decoder.PixelWidth;
                        int height = (int)decoder.PixelHeight;
                        Windows.Graphics.Imaging.PixelDataProvider dataprovider = await decoder.GetPixelDataAsync();
                        byte[] pixels = dataprovider.DetachPixelData();
                        wbsrcImage = new WriteableBitmap(width, height);
                        Stream pixelStream = wbsrcImage.PixelBuffer.AsStream();
    
                        //rgba in original   
                        //to display ,convert tobgra    
                        for (int i = 0; i < pixels.Length; i += 4)
                        {
                            byte temp = pixels[i];
                            pixels[i] = pixels[i + 2];
                            pixels[i + 2] = temp;
                        }
                        pixelStream.Write(pixels, 0, pixels.Length);
                        pixelStream.Dispose();
                        stream.Dispose();
                    }
    
                    ImageOne.Source = wbsrcImage;
                    ImageOne.Width = wbsrcImage.PixelWidth;
                    ImageOne.Height = wbsrcImage.PixelHeight;
                }
    
            }
    

     2.图片的保存. 将获得的WriteableBitmap保存起来. 比如你可以将Scale和Crop的图片保存起来.

            public async static Task SaveImage(WriteableBitmap src)
            {
                FileSavePicker save = new FileSavePicker();
                save.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                save.DefaultFileExtension = ".jpg";
                save.SuggestedFileName = "newimage";
                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();
                try
                {
                    Guid encoderId;
                    switch (savedItem.FileType.ToLower())
                    {
                        case ".jpg":
                            encoderId = BitmapEncoder.JpegEncoderId;
                            break;
                        case ".bmp":
                            encoderId = BitmapEncoder.BmpEncoderId;
                            break;
                        case ".png":
                        default:
                            encoderId = BitmapEncoder.PngEncoderId;
                            break;
    
                    }
    
                    IRandomAccessStream fileStream = await savedItem.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, fileStream);
                    Stream pixelStream = src.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    pixelStream.Read(pixels, 0, pixels.Length);
    
                    //pixal format shouldconvert to rgba8 
                    for (int i = 0; i < pixels.Length; i += 4)
                    {
                        byte temp = pixels[i];
                        pixels[i] = pixels[i + 2];
                        pixels[i + 2] = temp;
                    }
    
                    encoder.SetPixelData(
                      BitmapPixelFormat.Rgba8,
                      BitmapAlphaMode.Straight,
                      (uint)src.PixelWidth,
                      (uint)src.PixelHeight,
                      96, // Horizontal DPI 
                      96, // Vertical DPI 
                      pixels
                      );
                    await encoder.FlushAsync();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
    

    作者:Work Hard Work Smart
    出处:http://www.cnblogs.com/linlf03/
    欢迎任何形式的转载,未经作者同意,请保留此段声明!

  • 相关阅读:
    测试策略如何制定
    python atexit模块和register函数
    使用Redis实现异步消息队列
    python 处理中文 读取数据库输出全是问号
    TCP和UDP的区别和优缺点
    怎样ping网络
    ImportError: libpng12.so.0: cannot open shared object file: No such file or directory
    tensorrtx/retinaface/calibrator.cpp:4:31: 致命错误:opencv2/dnn/dnn.hpp:没有那个文件或目录
    编译tensorrtx/retinaface遇到报错/usr/local/cuda/include/vector_types.h(421): error: identifier "constexpr" is undefined
    RetinaFace.cpp:112:37: 错误:‘std::chrono’尚未声明
  • 原文地址:https://www.cnblogs.com/linlf03/p/2792726.html
Copyright © 2020-2023  润新知