Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read and write JPEG data on a per-pixel basis?

Tags:

c#

jpeg

The title pretty much explains my question. I would like to be able to read and write JPEG data on a per-pixel basis using C#.

I'm thinking something along the lines of CreateJPEG(x, y) which would set up a blank JPEG image in memory, and would give me a JPEG object, and then something like SetPixel(x, y, Color) and GetPixel(x, y) the latter of which would return a Color or something similar. You could then call an Apply() or Save() method, for example, to save the image in a standard JPEG-readable format (preferrably with compression options, but that's not necessary).

And I'm assuming some C# library or namespace makes this all a very easy process, I'd just like to know the best way to go about it.

like image 966
qJake Avatar asked Jul 07 '10 08:07

qJake


2 Answers

JPEG is not a processing format, it's a storage format.

As such, you don't actually use a JPEG image in memory, you just have an image. It's only when you store it that you pick the format, like PNG or JPEG.

As such, I believe you're looking for the Bitmap class in .NET.

like image 38
Lasse V. Karlsen Avatar answered Oct 23 '22 20:10

Lasse V. Karlsen


Have a look at the Bitmap class. For advanced drawing besides manipulating single pixel you will have to use the Graphics class.

var image = new Bitmap("foo.jpg");

var color = image.GetPixel(1, 2);
image.SetPixel(42, 42, Color.White);

image.Save("bar.jpg", ImageFormat.Jpeg);

As Lasse V. Karlsen mentions in his answer this will not really manipulate the JPEG file. The JPEG file will be decompressed, this image data will be altered, and on saving a new JPEG file is created from the altered image data.

This will lower the image quality because even recompressing an unaltered image does usually not yield a bit-identical JPEG file due to the nature of lossy JPEG compressions.

There are some operations that can be performed on JPEG files without decompressing and recompressing it - for example rotating by 90° - put manipulating single pixels does not fit in this category.

like image 174
Daniel Brückner Avatar answered Oct 23 '22 19:10

Daniel Brückner