Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP encode image to PNG

I get an image by URI (web or file system) and want to encode it into PNG and save to a temporary file:

var bin = new MemoryStream(raw).AsRandomAccessStream();  //raw is byte[]
var dec = await BitmapDecoder.CreateAsync(bin);
var pix = (await dec.GetPixelDataAsync()).DetachPixelData();

var res = new FileStream(Path.Combine(ApplicationData.Current.LocalFolder.Path, "tmp.png"), FileMode.Create);
var enc = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, res.AsRandomAccessStream());
enc.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, dec.PixelWidth, dec.PixelHeight, 96, 96, pix);
await enc.FlushAsync();  //hangs here
res.Dispose();

Problem is, this code hangs on the await enc.FlushAsync() line. Please help! Thanks.

like image 978
Mike Tsayper Avatar asked May 24 '16 07:05

Mike Tsayper


Video Answer


1 Answers

I don't know for sure why your code hangs -- but you're using several IDisposable thingies, which may be related. At any rate, here's some code that does pretty much what you're trying to do, and it does work:

StorageFile file = await ApplicationData.Current.TemporaryFolder
    .CreateFileAsync("image", CreationCollisionOption.GenerateUniqueName);
using (IRandomAccessStream outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    using (MemoryStream imageStream = new MemoryStream())
    {
        using (Stream pixelBufferStream = image.PixelBuffer.AsStream())
        {
            pixelBufferStream.CopyTo(imageStream);
        }

        BitmapEncoder encoder = await BitmapEncoder
            .CreateAsync(BitmapEncoder.PngEncoderId, outputStream);
        encoder.SetPixelData(
            BitmapPixelFormat.Bgra8,
            BitmapAlphaMode.Ignore,
            (uint)image.PixelWidth,
            (uint)image.PixelHeight,
            dpiX: 96,
            dpiY: 96,
            pixels: imageStream.ToArray());
        await encoder.FlushAsync();
    }
}

(My image is a WriteableBitmap; not sure what your raw is?)

like image 118
Petter Hesselberg Avatar answered Sep 28 '22 04:09

Petter Hesselberg