i simply want to load a .BMP file and get the Bitmap object in 24bit RGB format (or 32bit in RGB format).
All methods I tried return a Bitmap/Image object with PixelFormat = Format32bppArgb. Even if of course BMPs don't have alpha.
new Bitmap(System.Drawing.Image.FromFile(fileName, true));
new Bitmap(fileName);
I currently solve the problem by copying the first object to another in memory bitmap at 24bit RBG.
Is there a single method to do it?
Thanks
As far as I can tell it is not possible to specify the PixelFormat for loading bitmaps using the classes in System.Drawing. To convert the bitmap check this question: Converting Bitmap PixelFormats in C#
This is currently the top answer there:
Bitmap orig = new Bitmap(#"c:\temp\24bpp.bmp");
Bitmap clone = new Bitmap(orig.Width, orig.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
using (Graphics gr = Graphics.FromImage(clone)) {
gr.DrawImage(orig, new Rectangle(0, 0, clone.Width, clone.Height));
}
// Dispose orig as necessary..
One option would be to put that in a function which takes a filename and PixelFormat. That hides the ugly code, which has its ups and downs since it also hides the fact it is probably not that efficient.
According to the linked SO question using the Clone method not always works.
You can clone it to a RGB format one:
var bitmapInRgbFormat = loadedBitmap.Clone(new Rectangle(0, 0, loadedBitmap.Width, loadedBitmap.Height), PixelFormat.Format32bppRgb)
Exactly what do you mean by copying the first object to another?
To achieve what you want to do, meaning loading an image and converting it to 24 bit, just get the graphics context of a second bitmap that matches the size and that is RGB, and paint the original bitmap onto this one.
Related
I'm taking a screenshot of the screen, serializing the bitmap and sending it over the network. Overall this ends up being ~26KB of data transferred.
I'm trying to make this smaller. One thing I'm trying to do is converting the bitmap to greyscale. This is the function I'm using.
Public Function ConvertGreyscale(original As Bitmap) As Bitmap
Dim NewBitmap As New Bitmap(original.Width, original.Height)
Dim g As Graphics = Graphics.FromImage(NewBitmap)
Dim attributes As New ImageAttributes
attributes.SetColorMatrix(New ColorMatrix(New Single()() {New Single() {0.3F, 0.3F, 0.3F, 0, 0}, New Single() {0.59F, 0.59F, 0.59F, 0, 0}, New Single() {0.11F, 0.11F, 0.11F, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}}))
g.DrawImage(original, New Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes)
g.Dispose()
Return NewBitmap
End Function
This works fine, and i end up getting a greyscale image. Problem is, that the size of the bitmap doesn't change. It's still 26KB, even though it's greyscale. I'm thinking that the new bitmap that's being created is just a regular 32bppargb bitmap with a greyscale image stuck into it.
I tried doing:
Dim NewBitmap As New Bitmap(original.Width, original.Height, PixelFormat.Format16bppgreyscale)
but i end up getting an "out of memory error".
What am i doing wrong? Also, are there any other ways to minimize the size of my bitmap?
EDIT:
So in an effort to take baby steps to tackle this problem, I'm using this code to convert the 32bpp bitmap to a 16bpp bitmap
Dim clone = New Bitmap(tmpImg.Width, tmpImg.Height, Imaging.PixelFormat.Format16bppRgb565)
Using gr = Graphics.FromImage(clone)
gr.DrawImage(tmpImg, New Rectangle(0, 0, clone.Width, clone.Height))
End Using
I tried doing Format16bbpGreyscale or Format16bppRgb555, but both of those cause "Our of memory errors". The only one that seems to work is the Format16bppRgb256
Regardless, I'm doing my packet sniffing again, and changing the format to 16bppRgb265 INCREASES the size of the image packet from ~26KB to 29KB. So changing to this format seems to increase size. I don't understand ;_;
EDIT2:
I've found multiple ways to convert the image to greyscale now and/or changing the pixelformat of the bitmap to something smaller than 32bpp. Unfortunately none of this seems to decrease the size of the serialized bitmap when it's being sent over the network. Some things seem to even increase the size. Not sure what i can do.
I recommend checking out Aforge's AForge.Imaging.ColorReduction.ColorImageQuantizer .
It reduced a screenshot of a SO homepage from 96kB to 33kB (going to 16 colors) while maintaining readabilty much better that an equally reduced jpg. Reducing to 32 or 64 colors left almost no artifacts, other than color changes while still staying at 48kB.
It does take a few seconds for processing, though..
Here is a piece of code that uses the Aforge libraries.
using AForge.Imaging.ColorReduction;
void reduceColors(string inFile, string outFile, int numColors)
{
using (Bitmap image = new Bitmap(inFile) )
{
ColorImageQuantizer ciq = new ColorImageQuantizer(new MedianCutQuantizer());
Color[] colorTable = ciq.CalculatePalette(image, numColors);
using (Bitmap newImage = ciq.ReduceColors(image, numColors))
newImage.Save(outFile);
}
}
If you're interested I also have a home-grown piece of code, that results in 40% of the original size with perfext text, albeit a little color shift; it is very fast.
Converting to greyscale doesnt do much by itself because all you are doing is changing the RGB values of the pixels. Unfortunately many of the greyscale formats are not fully supported, though there are some opensource image libraries which will do this.
Significant reduction can be gotten using JPG and some quality reduction. 26kb for a full size (?) screenshot doesn't sound all that large (or it is only part of a screen?), and we dont know what your desired target size is. Here is how to reduce quality via JPG.
Dim jpgEncoder As ImageCodecInfo = GetJPGEncoder()
Dim myEncoder As System.Drawing.Imaging.Encoder =
System.Drawing.Imaging.Encoder.Quality
Dim jEncoderParams As New EncoderParameters(1)
' set the quality (100& here)
jEncoderParams.Param(0) = New EncoderParameter(myEncoder, 100&)
' dont do this...creates a false baseline for size tests
'Dim bmp As Bitmap = My.Resources.testimage
Using ms As New System.IO.MemoryStream(),
fs As New FileStream("C:\Temp\zser.bin", FileMode.Create),
bmp As New Bitmap(My.Computer.Screen.WorkingArea.Width,
My.Computer.Screen.WorkingArea.Height),
g As Graphics = Graphics.FromImage(bmp)
' get screen in (BMP format)
g.CopyFromScreen(0, 0, 0, 0, My.Computer.Screen.WorkingArea.Size)
' save image to memstream in desired format
bmp.Save(ms, Imaging.ImageFormat.Png)
' use jpgEncoder to control JPG quality/compression
'bmp.Save(ms, jpgEncoder , jEncoderParams)
ms.Position = 0
Dim bf As New BinaryFormatter
bf.Serialize(fs, ms) ' serialize memstr to file str
jEncoderParams.Dispose()
End Using
Metrics from a screen capture (ACTUAL size depends on screen size and what is on it; the size differences are what is important):
Method memstr size file size after BF
BMP 5,568,054 5438 (same)
PNG 266,624 261k
JPG 100 634,861 1025
JPG 90 277,575 513
The content of the image plays a role in determining the sizes etc. In this case, PNG seems best size/quality balance; you'd have to compress JPG quite a bit to get the same size but with much less quality.
An actual photo type image will result in much larger sizes: 19MB for a 2500x1900 image and almost 13MB for a PNG, so test using actual images.
So eventually I've figured out the problem.
Essentially i had to binary serialize a bitmap and transmit it over a network stream. And i was trying to decrease the size of the bitmap to make transfer faster.
.NET's "image" class seems to only support bitmaps in certain pixelformats. So no matter what i did to the image (greyscaled, lossy compression, whatever) the size would be the same because i wasn't change the pixelformat of the image, s i was just moving pixels around and changing their colors.
From what i know, there is no native class for JPGs or PNGs that i could serialize, so i was forced to use the image class with it's pixel formats.
One thing i tried was to convert the compressed, greyscaled image into a jpeg, and then convert that into a byte(), and then gzip and serialize that byte(). Problem is that resulted in a 2x increase in network data being transmitted for some reason.
An interesting quick note, is that when you serialize an image object, it is converted to PNG format (compressed), according to the network traffic i sniffed anyway. So there is some optimization that has been done by microsoft to make image serialization efficient.
So i was pretty much forced to use the image class, and just somehow figure out how to convert my image into the 1bpp or 8bpp pixelformats. The 16bpp formats (greyscale for instance) are randomly "unsupported" by microsoft, and just "don't work", and apparently never will. Of course MSDN doesn't mention any of this.
Converting my image to 8bpp or lower was impossible, because i would get "out of memory" errors for unknown reasons, or something about not being allowed to draw on indexed images.
The solution i finally found was the CopyToBpp() function from here:
http://www.wischik.com/lu/programmer/1bpp.html
That function, along with the many API's in it, allowed me to quickly convert my 32bpp Image into an 8bpp or even 1bbp image. Which could then be easily and efficiently serialized a binary formatter and sent over my network stream.
So now it works.
Any easy way? I am trying to convert the PixelFormat from 24 bits image to 16 bits RGB555 with dithering (for a portable device). I tested already a lot of approaches:
AForge.NET
FreeImage
http://www.codeproject.com/Articles/66341/A-Simple-Yet-Quite-Powerful-Palette-Quantizer-in-C
They all work poorly.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms536306(v=vs.85).aspx
I found a GDI+ wrapper, but this function is missing.
Thanks!
You can convert the image by using Bitmap class in the constructor pass the parameters for the conversion format and it will render the image with the PixelFormat you have mentioned.
Some code:
public static Bitmap ConvertTo16bpp(Image img) {
//you can also use Image.FromFile(fileName);//fileName can be absolute path of the image.
var bmp = new Bitmap(img.Width, img.Height,System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
using (var gr = Graphics.FromImage(bmp))
gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
return bmp;
}
Suggestions
If you have some simple requirements you would not probably need AForge.NET (An excellent library for image processing) and you may go with a simple solution,but that's your decision to make.
Links
system.drawing.imaging
system.drawing.imaging.pixelformat
Convert-24-bit-bmp-to-16-bit (Solution Adpated from)
The question is quite self explicative, I would like to use a 1bpp Bitmap because will help me (a lot) talking with a device that accept 1bbp bitmaps (well, 160x43 byte array that is a 160x43 bitmap image with 1bpp format).
While C# allows me to create 1bpp bitmaps, I would like to work on it with a Graphics object. But the program seems to behave strangely when I do any operation on this.
Is possible to do some graphic operations on those type of bitmaps?
my code snippet is quite short:
Bitmap bwImage = new Bitmap(160, 43, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
using (Graphics g = Graphics.FromImage(bwImage))
{
g.FillRectangle(Brushes.White, new Rectangle(0, 0, 160, 43));
g.DrawString("ciao sono francesco", Font, Brushes.Black, new RectangleF(0f, 0f, 159f, 42f));
}
When I do anything related to bitmaps after those calls. My bitmaps doesn't change (obviusly I'm talking about other bitmaps). Like if GDI is totally dead
Any ideas?
The Graphics class and the Graphics.FromImage method do not support indexed bitmaps. Please refere to the documentation for the Graphics.FromImage method on MSDN. A workaround for your problem would be to do all graphic operations on a supported bitmap format such as PixelFormat.Format32bppRgb and then convert the bitmap to a indexed bitmap. The conversion is straightforward. You will find a example of such a conversion here.
Hope, this helps.
If I have a .Net Bitmap, I can create from it a GDI bitmap by calling the Bitmap's GetHbitmap() method.
Bitmap bmp = new Bitmap(100, 100);
IntPtr gdiBmp = bmp.GetHbitmap();
This works fine, but every time you call GetHbitmap, Windows has to allocate the new memory that the returned IntPtr references.
What I'd like to do - if possible - is write a function (I know PInvoke will be necessary here) that also generates a GDI bitmap copy of a Bitmap, but that overwrites an existing chunk of memory already referenced by an IntPtr returned from GetHbitmap instead of allocating new memory. So it would look something like this (if it were an extension method of Bitmap):
// desired method signature:
void OverwriteHbitmap(IntPtr gdi)
{
}
// ex:
Bitmap bmp1 = new Bitmap(100, 100);
IntPtr gdi1 = bmp1.GetHbitmap();
Bitmap bmp2 = new Bitmap(100, 100);
bmp2.OverwriteHbitmap(gdi1); // gdi1 is still pointing to the same block
// of memory, which now contains the pixel data from bmp2
How can I do this? I assume I'll need to know the structure of a GDI bitmap, and probably I can use LockBits and BitmapData for this, but I'm not sure exactly how.
Clues for the bounty hunters:
Bitmap has a method LockBits which locks the bitmap in memory and returns a BitmapData object. The BitmapData object has a Scan0 property which is an IntPtr pointing to the start of the locked bitmap's pixel data (i.e it doesn't point to the bitmap's header a.k.a. the start of the bitmap itself).
I'm pretty sure the solution looks something like this:
Bitmap bmp1 = new Bitmap(100, 100);
IntPtr gdi1 = bmp1.GetHbitmap(); // now we have a pointer to a
// 100x100 GDI bitmap
Bitmap bmp2 = new Bitmap(100, 100);
BitmapData data = bmp2.LockBits();
IntPtr gdi1Data = gdi1 + 68; // magic number = whatever the size
// of a GDI bitmap header is
CopyMemory(data.Scan0, gdi1Data, 40000);
The solution does not have to be generic - it only needs to work for bitmaps with pixel format Format32bppArgb (the default GDI+ format).
I think you answered your own question: use LockBits.
See
How to: Use LockBits
and
Bob Powell - Locking Bits.
I used this method to rapidly draw fractals in a .NET (1.1!) program that I was writing for fun. Of all the methods that I experimented with, this was by far the fastest.
Create a Graphics from the IntPtr with Graphics.FromHdc and use Graphics.DrawImage to paste the Bitmap into it.
You should not assume that a HANDLE or HBITMAP is a pointer to anything. It can be implemented as an index into a handle table, key of a hash table, etc.
However, if you call the GDI GetObject function, the resultant BITMAP structure contains a pointer to the real bits.
Not sure if it would be as fast (I think in the case of the same pixel format for source and destination it will), but SetDIBits should do exactly what you want (replace the data in an existing HBITMAP).
I am messing around with Conway's Game of Life - http://en.wikipedia.org/wiki/Conway's_Game_of_Life
I started out coding algorithmns for winforms and now want to port my work onto windows mobile 6.1 (compact framework). I came across an article by Jon Skeet where he compared several different algorithmns for calculating next generations in the game. He used an array of bytes to store a cells state (alive or dead) and then he would copy this array to an 8bpp bitmap. For each new generation, he works out the state of each byte, then copies the array to a bitmap, then draws that bitmap to a picturebox.
void CreateInitialImage()
{
bitmap = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
ColorPalette palette = bitmap.Palette;
palette.Entries[0] = Color.Black;
palette.Entries[1] = Color.White;
bitmap.Palette = palette;
}
public Image Render()
{
Rectangle rect = new Rectangle(0, 0, Width, Height);
BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
Marshal.Copy(Data, 0, bmpData.Scan0, Data.Length);
bitmap.UnlockBits(bmpData);
return bitmap;
}
His code above is beautifully simple and very fast to render. Jon is using Windows Forms but now I want to port my own version of this onto Windows Mobile 6.1 (Compact Framework) but . . . .there is no way to format a bitmap to 8bpp in the cf.
Can anyone suggest a way of rendering an array of bytes to a drawable image in the CF. This array is created in code on the fly (it is NOT loaded from an image file on disk). I basically need to store an array of cells represented by bytes, they are either alive or dead and I then need to draw that array as an image. The game is particularly slow on the CF so I need to implement clever optimised algoritmns but also need to render as fast as possible and the above solution would be pretty dam perfect if only it was available on the compact framework.
Many thanks for any help
Any suggestions?
You could have a look at GDI+ for CF. It's basically a wrapper for most of the GDI implemented in WinCE. Here's a link to the source code and a writeup: http://community.opennetcf.com/articles/cf/archive/2007/10/31/using-gdi-on-windows-mobile.aspx
I think ImagingFactoryClass.CreateBitmapFromBuffer() looks like a good place to start.
Ok, how about this:
use the Bitmap.Save() method to save to a MemoryStream instead of a file;
when you save to the MemoryStream, you get to name the ImageFormat as "GIF" (this is equivalent to 8bpp in .Net, according to this: http://support.microsoft.com/kb/318343)
use MemoryStream.Write() to change whatever data you want in the image, or copy the data using MemoryStream.ToArray() if that jives better.
After you change the MemoryStream, you'll probably have to copy it back into the Bitmap, or make a new Bitmap. If you do make a new Bitmap, be sure to Dispose() the old one, to avoid memory leaks.
Hi Rocjoe and thanks again for the help, I have tried the following
Image bmp = new Bitmap(10, 10);
byte[] array = ImageToByteArray(bmp);
public byte[] ImageToByteArray(Image img)
{
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif );
return ms.ToArray();
}
The array coming back has over 870 bytes in it, It seems to hold all sorts of header info, padding and what have you. so again it does not work...