Bitmap - wrong coordinates - c#

When I take the mouse coordinates relative to the top left corner and set that pixel to a colour, that pixel is not at the mouse's position and it even differs from bitmap to bitmap. At one bitmap the coordinates seemed to be multiplied by 0.8 but the second one I tried was like *0.2. I tried using PageUnit = GraphicsUnit.Pixel;, that also didn't work. I think the bitmaps might be set to use different pixel size but even if that's the case, I don't know how to handle that.

Looks like your bitmaps have varying dpi settings.
You may need to correct them to be the same as the Graphics object has:
Bmp.SetResolution(g.DpiX, g.DpiY);
g.DrawImage(Bmp, 0, 0);

Related

Tranfer Contents inside a Rotated Polygon to Bitmap

I'm using C# WinForms.
The rotated polygon is drawn on a picturebox. The width and height of the rotated polygon is 101, 101. Now, I want to transfer the contents of rotated polygon to new bitmap of size 101,101
I tried to paint pixels of the rectangle using this code
for (int h = 0; h < pictureBox1.Image.Height; h++)
{
for (int w = 0; w < pictureBox1.Image.Width; w++)
{
if (IsPointInPolygon(rotatedpolygon, new PointF(w, h)))
{
g.FillRectangle(Brushes.Black, w, h, 1, 1); //paint pixel inside polygon
}
}
}
The pixels are painted in the following manner:
Now, how do I know which location on the rotated rectangle goes to which location in the new bitmap. That is how do i translate pixel co-ordinates of rotated rectangle to new bitmap.
or simply put, is it possible to map rows and columns from rotated rectangle to new bitmap as shown below?
Sorry, if the question is not clear.
What you asking to do is not literally possible. Look at your diagram:
On the left side, you've drawn pixels that are themselves oriented diagonally. But, that's not how the pixels actually are oriented in the source bitmap. The source bitmap will have square pixels oriented horizontally and vertically.
So, let's just look at a little bit of your original image:
Consider those four pixels. You can see in your drawing that, considered horizontally and vertically, the top and bottom pixels overlap the left and right pixels. More specifically, if we overlay the actual pixel orientations of the source bitmap with your proposed locations of source pixels, we get something like this:
As you can see, when you try to get the value of the pixel that will eventually become the top-right pixel of the target image, you are asking for the top pixel in that group of four. But that top pixel is actually made up of two different pixels in the original source image!
The bottom line: if the visual image that you are trying to copy will be rotated during the course of copying, there is no one-to-one correspondence between source and target pixels.
To be sure, resampling algorithms that handle this sort of geometric projection do apply concepts similar to that which you're proposing. But they do so in a mathematically sound way, in which pixels are necessarily merged or interpolated as necessary to map the square, horizontally- and vertically-oriented pixels from the source, to the square, horizontally- and vertically-oriented pixels in the target.
The only way you could get literally what you're asking for — to map the pixels on a one-to-one basis without any change in the actual pixel values themselves — would be to have a display that itself rotated.
Now, all that said: I claim that you're trying to solve a problem that not only is not solvable, but also is not worth solving.
Display resolution is so high on modern computing devices, even on the phone that you probably have next to you or in your pocket, that the resampling that occurs when you rotate bitmap images is of no consequence to the human perception of the bitmap.
Just do it the normal way. It will work fine.

C# : Issue with scaling graphics with when image is resized

I'd have a program that will allow you to draw lines over an image which will eventually be used for calculating distance.
To make things simple, my current image (which is in a PictureBox) is an image of a ruler. When you left click, a path is created and drawn.
Originally, to zoom in, I had it so that a new bitmap would be created with the images new size and I was able to use Graphics.ScaleTransform and it worked fine but it would just crop the image.
I needed the image to actually change width and height so now what I'm doing is just adding/subtracting a constant zoom amount to the width & height when zooming in/out.
With this approach, I can't seem to scale the graphics and the paths are skewed into different directions and not the right size when the image is zoomed in.
I completely understand why this is happening, because the image is getting larger and the graphics are staying the same, I just need whatever math is required to scale the graphics.
I've tried using Graphics.ScaleTransform as well as moving the graphics x & y to their current position + the current zoom amount (offset)
As directed by #TaW I changed the zooming functionality to calculate a new Width & Height based on the whatever zoom was applied then create a new Bitmap which contained the original image with the new width and height.

Not getting exact result using the DrawImage function

Okay, so I have an Image which holds my tile set. Then I have my PictureBox used as my "game screen". All the code does is takes a snippet of my tile set (a tile) and place it on the game screen.
Here's my code.
private void picMap_Click(object sender, EventArgs e)
{
//screenMain = picMap.CreateGraphics();
// Create image.
//gfxTiles = Image.FromFile(#Program.resourceMapFilePath + "poatiles.png");
// Create coordinates for upper-left corner of image.
int x = 0;
int y = 0;
// Create rectangle for source image.
Rectangle srcRect = new Rectangle(16, 16, 16, 16);
GraphicsUnit units = GraphicsUnit.Pixel;
// Draw image to screen.
screenMain.DrawImage(gfxTiles, x, y, srcRect, units);
screenMain.DrawImage(gfxTiles, 16, 0, srcRect, units);
screenMain.DrawImage(gfxTiles, 32, 0, srcRect, units);
screenMain.DrawImage(gfxTiles, 16, 16, srcRect, units);
}
And here is my output:
Any reason why that space between each "tile" is there (it's a 2 pixels gap)? I could ghetto rig the code, but I plan to use algebra to programatically figure out where tiles need to go, etc etc, so a ghetto rig would work, but to do that throughout the entire game would be troublesome, and at the very least, sloppy.
I think the call to DrawImage is okay. In the image you posted it looks like 16x16 tiles next to each other. I'd check poatiles.png. I'm not sure what's at Rectangle(16, 16, 16, 16) in it. It may not be what you think.
EDIT: I don't know what to say. I made a png almost the size of poatiles and put a 16x16 square in it a 16,16, and it drew exactly like you'd expect.
The code looks fine and since it works on smaller images, the only thing I can think of is there's a problem with poatiles.
There's the following comment in MSDN about Graphics.DrawImage Method (Image, Int32, Int32, Rectangle, GraphicsUnit)
This method draws a portion of an image using its physical size, so
the image portion will have its correct size in inches regardless of
the resolution (dots per inch) of the display device. For example,
suppose an image portion has a pixel width of 216 and a horizontal
resolution of 72 dots per inch. If you call this method to draw that
image portion on a device that has a resolution of 96 dots per inch,
the pixel width of the rendered image portion will be (216/72)*96 =
288.
Since you're specifying pixels as the unit I'd expect it to ignore that. But in the absence of better ideas you might want to compare the dpi of poatiles versus the smaller images. (Image.HorizontalResolution & Image.VerticalResolution)
I'm not sure that all of the information is there to start with, but here's some suggestions I have from looking at what you've done so far.
1) Check poatiles.png to make sure that it's definitely a 16x16 pixel image with no black pixels around it.
2) It seems odd that your Rectangle has four int's in its constructor. A rectangle should usually only have a width and height (if any sides have different lengths, then it's not a true rectangle!)
3) You might want to determine your positions on screen by multiplying by width and height of the Rectangle that you're trying to draw and adding that value to the origin (0,0).

Change background colour of an anti-aliased image using C# with anti-aliasing

I have an image where I need to change the background colour (E.g. changing the background of the example image below to blue).
However, the image is anti-aliased so I cannot simply do a replace of the background colour with a different colour.
One way I have tried is creating a second image that is just the background and changing the colour of that and merging the two images into one, however this does not work as the border between the two images is fuzzy.
Is there any way to do this, or some other way to achieve this that I have no considered?
Example image
Just using GDI+
Image image = Image.FromFile("cloud.png");
Bitmap bmp = new Bitmap(image.Width, image.Height);
using (Graphics g = Graphics.FromImage(bmp)) {
g.Clear(Color.SkyBlue);
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.PixelOffsetMode = PixelOffsetMode.None;
g.DrawImage(image, Point.Empty);
}
resulted in:
Abstractly
Each pixel in your image is a (R, G, B) vector, where each component is in the range [0, 1]. You want a transform, T, that will convert all of the pixels in your image to a new (R', G', B') under the following constraints:
black should stay black
T(0, 0, 0) = (0, 0, 0)
white should become your chosen color C*
T(1, 1, 1) = C*
A straightforward way to do this is to choose the following transform T:
T(c) = C* .* c (where .* denotes element-wise multiplication)
This is just standard image multiplication.
Concretely
If you're not worried about performance, you can use the (very slow) methods GetPixel and SetPixel on your Bitmap to apply this transform for each pixel in it. If it's not clear how to do this, just say so in a comment and I'll add a detailed explanation for that part.
Comparison
Compare this to the method presented by LarsTech. The method presented here is on the top; the method presented by LarsTech is on the bottom. Notice the undesirable edge effects on the bottom icon (white haze on the edges).
And here is the image difference of the two:
Afterthought
If your source image has a transparent (i.e. transparent-white) background and black foreground (as in your example), then you can simply make your transform T(a, r, g, b) = (a, 0, 0, 0) then draw your image on top of whatever background color you want, as LarsTech suggested.
If it is a uniform colour you want to replace you could convert this to an alpha. I wouldn't like to code it myself!
You could use GIMP's Color To Alpha source code (It's GPL), here's a version of it
P.S. Not sure how to get the latest.
Background removal /replacement, IMO is more art than science, you’ll not find one algorithm fit all solution for this BUT depending on how desperate or interested you are in solving this problem, you may want to consider the following explanation:
Let’s assume you have a color image.
Use your choice of decoding mechanism and generate a gray scale / luminosity image of your color image.
Plot a graph (metaphorically speaking) of numeric value of the pixel(x) vs number of pixels in the image for that value(y). Aka. a luminosity histogram.
Now if your background is large enough (or small), you’d see a part of the graph representing the distribution of a range of pixels which constitute your background. You may want to select a slightly wider range to handle the anti-aliasing (based on a fixed offset that you define if you are dealing with similar images) and call it the luminosity range for your background.
It would make your life easier if you know at least one pixel (sample/median pixel value) out of the range of pixels which defines your background, that way you can ‘look up’ the part of the graph which defines your background.
Once you have the range of luminosity pixels for the background, you may run through the original image pixels, compare their luminosity values with the range you have, if it falls within, replace the pixel in the original image with the desired color, preferably luminosity shifted based on the original pixel and the sample pixel, so that the replaced background looks anti-aliased too.
This is not a perfect solution and there are a lot of scenarios where it might fail / partially fail, but again it would work for the sample image that you had attached with your question.
Also there are a lot of performance improvement opportunities, including GPGPU etc.
Another possible solution would be to use some of the pre-built third party image processing libraries, there are a few open source such as Camellia but I am not sure of what features are provided and how sophisticated they are.

Scaling and printing a Bitmap object

I have a Bitmap object created by drawing several controls with the DrawToBitmap method. I would now like to print the bitmap. However, the bitmap is too large to fit on a single page and so it must be scaled down. I'm trying to do that using the following overload of DrawImage:
public void PrintPageHandler(object sender, PrintPageEventArgs e)
{
Bitmap bitmap = GetBitmap();
Rectangle destRect = new Rectangle(
e.MarginBounds.X,
e.MarginBounds.Y,
e.MarginBounds.Width,
e.MarginBounds.Width * bitmap.Height / bitmap.Width);
e.Graphics.DrawImage(
bitmap,
destRect,
0,
0,
bitmap.Width,
bitmap.Height,
System.Drawing.GraphicsUnit.Pixel);
}
Note that the destRect width and height are constructed like this because the bitmap is much wider than it is tall (i.e. width is always the limiting dimension).
My problem is that the image ends up being very blurry when it's printed. Am I scaling this incorrectly? I have a feeling there may be some issue with a GraphicsUnit mismatch between e.MarginBounds and the image dimensions. Any help would be appreciated.
[UPDATE]
I tried resizing the bitmap using the method given in the comment below, but the image still prints blurry. For testing, I saved both the original and resized bitmap to files, opened them in Windows Photo Viewer, and tried to print them from there. The resized image prints blurry like it does from within my c# application, but the original image prints beautifully; whatever algorithm Windows Photo Viewer uses to resize to a single page did not cause the image to get blurred.
I wonder, could Windows Photo Viewer be increasing the pixel density when it resizes for printing? Maybe that's why resizing it in code is causing it to get blurred; the origin pixel density is insufficient to display the scaled down image clearly.
It doesn't look like you are preserving the aspect ratio. You need to calculate the ratio of the width to height of the original image and make sure to scale the output image so that it's dimensions have the same ratio.
Basically:
1 - Calculate the aspect ratio.
2 - Find the largest dimension of the target size.
3 - Resize the output so that the largest dimensions matches, and set the smaller dimension to the larger one multiplied by the ratio.
EDIT
Check the graphics.dpiX and .DpiY proeprties to see if your printer has a different DPI going horizontally from vertically. If they are different you will have to apply some additional adjustments to the dimensions.

Categories

Resources