Win10 UWP Read Save WriteableBitmap, BitmapImage

Source: Internet
Author: User
Tags creative commons attribution

We are in the UWP, often used images, data structures are BitmapImage and writeablebitmap. As for the difference between BitmapImage and WriteableBitmap, I will not say it here. The main talk is BitmapImage and writeablebitmap, binary byte of the mutual transfer.


Let's start by writing a simple XAML

       <Image x:name="Img" Height="$" Width="200"  HorizontalAlignment="Center" Source="Assets/splashscreen.png" >                </Image>        <button Margin="10,300,10,10" Content="OK"  click ="Button_onclick" ></Button>

The picture I used was a new one.

Save WriteableBitmap to File
    private static Async Task Savewriteablebitmapimagefile (writeablebitmap image, StorageFile file) {//bitmapen        Coder storage format Guid bitmapencoderguid = Bitmapencoder.jpegencoderid; string filename = file.        Name; if (filename.        EndsWith ("jpg")) {bitmapencoderguid = Bitmapencoder.jpegencoderid; } else if (filename.        EndsWith ("PNG")) {bitmapencoderguid = Bitmapencoder.pngencoderid; } else if (filename.        EndsWith ("BMP")) {bitmapencoderguid = Bitmapencoder.bmpencoderid; } else if (filename.        EndsWith ("TIFF")) {bitmapencoderguid = Bitmapencoder.tiffencoderid; } else if (filename.        EndsWith ("gif")) {bitmapencoderguid = Bitmapencoder.gifencoderid; The using (Irandomaccessstream stream = await file. OpenAsync (Fileaccessmode.readwrite, Storageopenoptions.none)) {Bitmapencoder encoder = await Bitmapenco DEr.            Createasync (Bitmapencoderguid, stream); Stream Pixelstream = image.            Pixelbuffer.asstream ();            byte[] pixels = new Byte[pixelstream.length]; Await pixelstream.readasync (pixels, 0, pixels.            Length); Encoder. Setpixeldata (Bitmappixelformat.bgra8, Bitmapalphamode.ignore, (UINT) image. Pixelwidth, (UINT) image.            Pixelheight, 96.0, 96.0, pixels); Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync (            Imgstream); Windows.Graphics.Imaging.PixelDataProvider PXPRD = await decoder. Getpixeldataasync (Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, New Windows.Graphics.Imaging.BitmapTransform (), Windows.Graphics.Imaging.ExifOrientationMode.RespectExifOrientation,        Windows.Graphics.Imaging.ColorManagementMode.DoNotColorManage);    Await encoder.        Flushasync (); }    }
Read WriteableBitmap from a file
        privatestaticasyncOpenWriteableBitmapFile(StorageFile file)        {            usingawait file.OpenAsync(FileAccessMode.Read))            {                await BitmapDecoder.CreateAsync(stream);                new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);                image.SetSource(stream);                return image;            }        }
ImageSource Turn byte[]

ImageSource can be BitmapImage, WriteableBitmap, if it is writeablebitmap, then the direct conversion

WriteableBitmap Turn byte[]

bitmap.PixelBuffer.ToArray();
Image Turn byte[]

If our imagesource is BitmapImage, then we cannot use the method above, directly save WriteableBitmap, we can use

privateasync Task<stringToBase64(Image control){    varnew RenderTargetBitmap();    await bitmap.RenderAsync(control);    returnawait ToBase64(bitmap);}

If ImageSource is WriteableBitmap, save directly

We use byte[] in the transmission is not good, can not be used in the HTTP transmission (not necessarily can not), so we turn it into Base64, I provide a lot of ways to base64 the array, the file to Base64. The code is https://codepaste.net/ijx28i copy.

//writeablebitmap turn byte[]Private Asynctask<string>ToBase64(WriteableBitmap bitmap) {varbytes = Bitmap. Pixelbuffer.toarray ();return awaitToBase64 (Bytes, (UINT) bitmap. Pixelwidth, (UINT) bitmap. Pixelheight);}Private Asynctask<string>ToBase64(StorageFile bitmap) {varstream =awaitBitmap. OpenAsync (Windows.Storage.FileAccessMode.Read);varDecoder =awaitBitmapdecoder.createasync (stream);varpixels =awaitDecoder. Getpixeldataasync ();varbytes = pixels. Detachpixeldata ();return awaitToBase64 (Bytes, (UINT) decoder. Pixelwidth, (UINT) decoder. Pixelheight, decoder. Dpix, decoder. DPIY);}Private Asynctask<string>ToBase64(RenderTargetBitmap bitmap) {varbytes = (awaitBitmap. Getpixelsasync ()). ToArray ();return awaitToBase64 (Bytes, (UINT) bitmap. Pixelwidth, (UINT) bitmap. Pixelheight);}Private Asynctask<string>ToBase64(byte[] Image,UINTHeightUINTWidthDoubleDpix = the,DoubleDpiy = the){//Encode image    varencoded =NewInmemoryrandomaccessstream ();varEncoder =awaitBitmapencoder.createasync (bitmapencoder.pngencoderid, encoded); Encoder. Setpixeldata (Bitmappixelformat.bgra8, bitmapalphamode.straight, height, width, dpix, dpiy, image);awaitEncoder.    Flushasync (); Encoded. Seek (0);//Read bytes    varbytes =New byte[Encoded. Size];awaitEncoded. Asstream (). Readasync (Bytes,0, bytes. Length);//Create Base64    returnConvert.tobase64string (bytes);}Private AsyncTask<imagesource>FromBase64(stringBase64) {//Read stream    varbytes = convert.frombase64string (base64);varImage = bytes. Asbuffer (). Asstream (). Asrandomaccessstream ();//Decode image    varDecoder =awaitBitmapdecoder.createasync (image); Image. Seek (0);//Create bitmap    varOutput =NewWriteableBitmap ((int) decoder. Pixelheight, (int) decoder. Pixelwidth);awaitOutput. Setsourceasync (image);returnOutput;}

Above code Source: https://codepaste.net/ijx28i

Read BitmapImage from a file
        privateasyncOpenBitmapImageFile(StorageFile file)        {            varawait file.OpenReadAsync();            varnew BitmapImage();            await bitmap.SetSourceAsync(fileStream);            return bitmap;        }
BitmapImage Turn WriteableBitmap

I use the http://www.cnblogs.com/cjw1115/p/5164327.html, direct WriteableBitmap bitmap = imageSource as WriteableBitmap; bitmap to NULL, so I continue to look online, as if I did not see the UWP can turn, only Win7

In fact, the great God has said that the source of the image is WriteableBitmap, so he can turn.

The BitmapImage of the UWP cannot be converted to byte[] or writeablebitmap. This sentence is wrong.

January 4, 2017 21:45:37

After a few months, I found out that our BitmapImage could turn byte[]

We can convert it to writeablebitmap by taking BitmapImage's urisource, and we can use it to get BitmapImage.

If you want to use BitmapImage UriSource to WriteableBitmap, you need to Writeablebitmapex. He was a library that everyone liked in WPF. How to install Writeablebitmapex, actually have nuget basically no problem.

Search Writeablebitmapex Nuget

And then I found out what we wanted, as if I didn't know.

I knew I could use it.WriteableBitmap image = await BitmapFactory.New(1, 1).FromContent((BitmapImage).UriSource);

Then turn byte[] How to do, with WriteableBitmap, below I also do not know, do not ask me.

If you use BitmapImage picture is SetSource, then I will not.

Get the color of the mouse click in the picture

Get the mouse click on that point, the color of the picture. What about the interface outside the picture? Actually we can also put the interface and then get it.

Then we need to first use TAP in Image, dummy source is BitmapImage

Premise installation Writeablebitmapex, if our viewmodel has a BitmapImage image, then we can use

            varas//鼠标点击的在哪            await BitmapFactory.New(11//我上面说的如何把 BitmapImage 转 WriteableBitmapEx            var temp = image.GetPixel((int) position.X, (int) position.Y);            string str = $"R: {temp.R} G: {temp.G} B: {temp.B} ";

Gets the color of the mouse click in the picture. This method sometimes blows up, and it's all 255.

Code: Https://github.com/lindexi/UWP/tree/master/uwp/src/ImageMoseClick

Get DPI

You can use the following code to get the image dpi.

My pictures are obtained from the solution and can be obtained from any location, as long as they can be converted to Irandomaccessstream

varawait StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/lindexi.png"usingawait file.OpenReadAsync()) {                     await BitmapDecoder.CreateAsync(BitmapDecoder.PngDecoderId, stream);      var DpiX = decoder.DpiX;     var DpiY = decoder.DpiY;                  }

If you need to save your network pictures locally, go to the Win10 UWP to store your network pictures locally

See also: http://www.cnblogs.com/cjw1115/p/5164327.html

Http://www.cnblogs.com/yuanforprogram/p/4819307.html

http://stackoverflow.com/questions/41439543/ How-can-i-get-the-pixel-color-of-an-image-at-the-current-pointer-position-in-a-u

http://lindexi.oschina.io/lindexi/post/win10-uwp-%E8%AF%BB%E5%8F%96%E4%BF%9D%E5%AD%98WriteableBitmap-BitmapImage/

Http://www.cnblogs.com/mqxs/p/5707620.html


This work is licensed under the Creative Commons Attribution-NonCommercial use-Share 4.0 International license agreement in the same way. Welcome to reprint, use, republish, but be sure to keep the article Attribution Lindesi (including Link: http://blog.csdn.net/lindexi_gd), not for commercial purposes, based on the modified works of this article must be issued with the same license. If you have any questions, please contact me.

Win10 UWP Read Save WriteableBitmap, BitmapImage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.