Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte array or matrix to BitMap

I am currently having the following problem: I want to convert a byte array 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 into a bitmap without having to set pixel by pixel with bitmap.setPixel because it takes too long.

Any suggestions? Thanks in advance!

like image 927
waclock Avatar asked Jun 07 '12 14:06

waclock


People also ask

How do I save a byte array as a picture?

Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter). Finally, Write the image to using the write() method of the ImageIo class.

How do I convert a bitmap to a byte?

In addition, you can simply convert byte array to Bitmap . var bmp = new Bitmap(new MemoryStream(imgByte)); You can also get Bitmap from file Path directly. Save this answer.

What is byte array used for?

A byte array is an array of bytes (tautology FTW!). You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

Why do we use byte array in Java?

We can use a byte array to store the collection of binary data.


1 Answers

If you have the byte[] of the pixels, and the width and height, then you can use BitmapData to write the bytes to the bitmap since you also know the format. Here's 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 minimum:

using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
like image 117
vcsjones Avatar answered Sep 30 '22 14:09

vcsjones