Encode a Bitmap as a Jpeg - c#

First, this question is NOT about "how to save a Bitmap as a jpeg on your disk?"
I can't find (or think of) a way of converting a Bitmap with Jpeg compression, but keep it as a Bitmap object. MSDN clearly shows how to save a Bitmap as a JPEG, but what I'm looking for is how to apply the encoding/compression to the Bitmap object, so I can still pass it around, in my code, without referencing the file.
One of the reasons behind that would be a helper class that handles bitmap, but shouldn't be aware of the persistency method used.

All images are bitmaps when loaded into program memory. Specific compressions are typically utilized when writing to disk, and decompressing when reading from disk.
If you're worried about the in-memory footprint of an image you could zip-compress the bytes and pass the byte array around internally. Zipping would be good for lossless compression of an image. Don't forget that many image compressions have different levels of losiness (sp?) In other words, the compression throws away data to store the image in the smallest number of bytes possible.
De/compression is also a performance tradeoff in that you're trading memory footprint for processing time. And in any case, unless you get really fancy, the image does need to be a bitmap if you need to manipulate it in any way.
Here is an answer for a somewhat similar question which you might find interesting.

Bitmap does not support encoded in-memory storage. It is always unencoded (see the PixelFormat enum). Problably you need to write your own wrapper class/abstraction, or give up on that idea.

var stream = new MemoryStream()
Bitmap.Save(Stream, ImageFormat)
Does it what you need?

Related

Processing on large bitmaps (up to 3GB)

I'm working on some university project and got stuck with memory issue.
I load a bitmap which takes about 1,5GB on HDD with code below:
Bitmap bmp = new Bitmap(pathToFile);
The issue is that the newly created Bitmap object uses about 3,5GB of RAM which is something I can't understand (that's really BIG wrapper :E). I need to get to the pixel array, and the use of Bitmap class is really helpful (I use LockBits() method later, and process the array byte per byte) but in this case it's total blocker. So here is my question:
Is there any easy way to extract the pixel array without lending additional 2gb?
I'm using c# just to extract the needed array, which is later processed in c++ - maybe I can extract all needed data in c++ (but conversion issue appears here - I'm concentrating on 24bgr format)?
PS: I need to keep the whole bitmap in memory so splitting it into parts is no solution.
PS2: Just to clarify some issues: I know the difference between file extension and file format. The loaded file is uncompressed bitmap 3 bytes per pixel of size ~1.42GB (16k x 32k pixels), so why Bitmap object is more than two times bigger? Any decompressing issues and converting into other format aren't taking place.
Consider using Memory Mapped Files to access your HUGE data :).
An example focused on what you need can be found here: http://visualstudiomagazine.com/articles/2010/06/23/memory-mapped-files.aspx
It's in managed code but you might as well use it from equivalent native code.
Let me know if you need more details.
You can use this solution , Work with bitmaps faster in C#
http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp
Or you can use memory mapped files
http://visualstudiomagazine.com/articles/2010/06/23/memory-mapped-files.aspx
You can stop memory caching.
Instead of
Bitmap bmp = new Bitmap(pathToFile);
Use
var bmp = (Bitmap)Image.FromStream(sourceFileStream, false, false);
see https://stackoverflow.com/a/47424918/887092

Converting Bitmap to Binary Array performance

I do have a Bitmap Array that contains more than 500 Bitmaps object. I need to convert each single Bitmap object within the Array into a binary Array. I'm using the MemoryStream class to achieve this:
using (MemoryStream ms = new MemoryStream())
{
images[0].Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] byteData = ms.ToArray();
}
I would like to know if there is other way to achieve this. I'm not sure how expensive is this process.
Thanks
I've done some speed tests and converting to ImageFormat.Bmp is the fastest. It doesn't need to do any compression. Though the best format will also depend on what you plan to do with the data after that.
It's also worth considering where the Bitmaps came from in the first place. If you're loading them in from a file it may be worth it to switch things around and read the file data in first, then create your Bitmap objects from it after that.
By choosing Gif you are making a CPU/memory trade off which you most likely don't want. Specifically the Gif is going to be smaller but is going to take some time to compress (unless the images are already in the format) relative to using a BMP.
If you are copying these around enough that you have memory bandwidth issues (and can't fix that) this is a good idea, but otherwise you should stick with BMP. Really though, for 500 images I would expect this to take 1-2 seconds at the most so you probably don't need to worry about this sort of micro optimization. If its taking to long you can move to unmanaged code which will likely perform better because you will have finer control over memory allocations and copies.

File.WriteAllBytes or FileStream.Write

What's the difference between File.WriteAllBytes and FileStream.Write/WriteBytes? I have a bitmap object that and I want to create a new bmp/jpg/png on disk. I think I read somewhere that WriteAllBytes uses FileStream.Write underneath?
WriteAllBytes is just a convinience method, that wraps the underlying Stream operations. (Create a file, write to stream, close stream, etc). Use it if it fits your needs. If you need more control on the underlying operations, fallback to using a Streamor similar.
It is all about using the right abstraction for the task.
Use WriteAllBytes to just save all the bytes, use Write if you need to watch the progress.
You're on the wrong track with this. Saving a bitmap object requires Image.Save(). That's a method that knows how to use an image encoder to convert a bitmap into the bytes that another program (or yours) can load back. There are several image encoders, you can select the one you want with the Save() overload that lets you pick the ImageFormat. The BMP format is the native Windows format, it is uncompressed. The PNG format is nice, it is a compressed lossless format. The JPEG format is a compressed lossy format, good for photos. File size is big to small in order.
You should use WriteAllBytes if you want to save a bitmap.

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

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.
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.
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.

Compress image in .NET

How can i compress and image file(*bmp,*jpeg) in C#,
I have to display some images as background on my controls, i m using following code to scale my image
Bitmap orgBitmap = new Bitmap(_filePath);
Bitmap regBitmap = new Bitmap(reqSize.Width, reqSize.Height);
using (Graphics gr = Graphics.FromImage(reqBitmap))
{
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
gr.DrawImage(bmp, new RectangleF(0, 0, reqSize.Width, reqSize.Height));
}
It giving me the required bitmap.
My problem is if orginal bitmap is to heavy(2 MB) then when i load 50 image it feed all my memory, i want to compress the image as much i can without losing the so much quality,How can i do the same in .NET ?
Do you definitely need the large images to be present at execution time? Could you resize them (or save them at a slightly lower quality) using an image editing program (Photoshop, Paintshop Pro etc) beforehand? There seems to be little point in doing the work every time you run - especially as editing tools are likely to do a better job anyway.
Of course, this won't work if it's something like the user picking arbitrary images from their hard disk.
Another point: are you disposing of the bitmaps when you're finished with them? You aren't showing that in your code... if you're not disposing of the original (large) bitmaps then you'll be at the mercy of finalizers to release the unmanaged resources. The finalizers will also delay garbage collection of those objects.
JPEG always lose something, PNG don't.
This is how you encode and decode PNG with C#:
http://msdn.microsoft.com/en-us/library/aa970062.aspx
Perhaps I'm misunderstanding things, but why not convert the bitmaps to jpg's before you import them into your project as control backgrounds?
Good luck compressing JPEG. :) It's compressed already. As for your BMPs, make them JPEGs.

Categories

Resources