Byte array or matrix for BitMap

I am currently having the following problem: I want to convert an array of bytes that comes from a file with the following configuration:

Byte1: R color of pixel 0,0. Byte2: G color of pixel 0,0. Byte3: B color of pixel 0,0. Byte4: R color of pixel 0,1. ... ByteN: R color of pixel n,n. 

So what I want to do is convert these bytes to a bitmap without having to set pixel by pixel with bitmap.setPixel , because it takes too much time.

Any suggestions? Thanks in advance!

+6
source share
1 answer

If you have byte[] pixels and the width and height, you can use BitmapData to write bytes to the bitmap, since you also know the format. Here is an example:

 //Your actual bytes byte[] bytes = {255, 0, 0, 0, 0, 255}; var width = 2; var height = 1; //Make sure to clean up resources var bitmap = new Bitmap(width, height); var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); Marshal.Copy(bytes, 0, data.Scan0, bytes.Length); bitmap.UnlockBits(data); 

This is a very fast operation.

You will need to import these three namespaces at the top of your C # file, at a minimum:

 using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; 
+11
source

Source: https://habr.com/ru/post/917532/


All Articles