by
51 6
1
4
46
2
Tagged
Specified
Tuned
OpenSource
Created
Modified Sep 25, 2019

Published on:

FrameworkUWP
InputName0imagePixels
InputName1width
InputName2dpi
InputName3frame
InputType0byte[]
InputType1int
InputType2int
InputType3Rect
Languagecsharp
LicenseMIT_X11
MethodNameImageFromBytes
OutputTypeTask<InMemoryRandomAccessStream>

How can I get an image from raw binary pixel content?

Given a raw binary content, this gives me a stream that can be easily turned into an Image
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/4361271/How-can-I-get-an-image-from-raw-binary-p?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
public static async Task<InMemoryRandomAccessStream> ImageFromBytes(this byte[] imagePixels, int width, int dpi, Rect frame) { //BitmapImage bitmap = new BitmapImage(); int xStart = (int)frame.X; int yStart = (int)frame.Y; int frameWidth = (int)frame.Width; int frameHeight = (int)frame.Height; byte[] framePixels = new byte[4 * frameWidth * frameHeight]; for (int y = 0; y < frameHeight; y++) { for (int x = 0; x < frameWidth; x++) { int frameOffset = (4 * y * frameWidth) + (4 * x); int imageOffset = (4 * (y + yStart) * width) + (4 * (x + xStart)); framePixels[frameOffset] = imagePixels[imageOffset]; framePixels[frameOffset + 1] = imagePixels[imageOffset + 1]; framePixels[frameOffset + 2] = imagePixels[imageOffset + 2]; framePixels[frameOffset + 3] = imagePixels[imageOffset + 3]; } } InMemoryRandomAccessStream bitmapStream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, bitmapStream); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, (uint)frameWidth, (uint)frameHeight, dpi, dpi, framePixels); try { await encoder.FlushAsync(); } catch { return bitmapStream; } return bitmapStream; }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus