C#: Retain size despite different resolution using Graphics.DrawImage - c#

I am trying to draw two images side-by-side using the C# Drawing namespace.
Here is a very simple example that assumes we have two images of the same height:
Image[] oldImages = GetOldImages();
var newImage = new Bitmap(oldImages[0].Width + oldImages[1].Width, 800);
using (var newImageGraphics = Graphics.FromImage(newImage))
{
newImageGraphics.DrawImage(oldImages[0], 0, 0);
newImageGraphics.DrawImage(oldImages[1], oldImage[0].Width, 0);
newImageGraphics.Save();
}
This works OK if the resolution of the two old images are the same.
However, if the resolutions are different then the image is resized, causing problems. For example, if the first image has a different resolution, then the second image will be positioned incorrectly.
Does anyone know how I can fix this problem easily? Ideally I want the original image's height and width to remain the same when they are drawn on to the new image.

Try this trick:
Bitmap picture_1 = new Bitmap(picture_1_path);
Graphics graphics = Graphics.FromImage(picture_1);
Bitmap picture_2 = new Bitmap(picture_2_path);
picture_2.SetResolution(graphics.DpiX, graphics.DpiY);
//Then do with pictures anything

Basically you'll need to resize the second image before adding to the new image.
Though as you say you want to retain the original height and width you'll need to change the canvas size of the second image. This increases the size of the image by adding empty space around the actual image. If the second image is larger than the first you'll need to do this to the first image instead.

Related

Rendering WPF to PNG produces blank image

I am trying to render a figure to a PNG using WPF (rather than the old GDI API) and the result is always blank.
I am writing a small program that will produce images routes around a warehouse to various items. I am using WPF API for drawing rather than the old GDI API as the images need to be both saved to disk and displayed within a WPF application. The problem is that all of the png files that it produces are currently entirely black.
To reduce the scope of the problem and prove that it was not a problem with code for drawing the map I made a minimal test method that should simply render a red circle on a black background. However the result is still an entirely black.
[TestMethod]
public void DrawingTest()
{
//define the dimensions of the test image
int width = 100;
int height = 100;
int dpi = 100;
//define where the image should be saved
var path = #"C:\temp\DrawingTest.png";
//create a bitmap to render the image into
RenderTargetBitmap bitmap = new RenderTargetBitmap(
width, height, dpi, dpi, PixelFormats.Default);
//create a drawing context to draw the image onto
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext canvas = drawingVisual.RenderOpen())
{
//draw a circle
canvas.DrawEllipse(Brushes.Red, new Pen(Brushes.Red, 1), new System.Windows.Point(50, 50), 50, 50);
//render the image into a bitmap
bitmap.Render(drawingVisual);
}
//create the file encoder
var encoder = new PngBitmapEncoder();
//encode the bitmap in PNG format
encoder.Frames.Clear();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
//make sure that the file can be saved in this location
var directory = System.IO.Path.GetDirectoryName(path);
if (!System.IO.Directory.Exists(directory))
System.IO.Directory.CreateDirectory(directory);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
//save the map to file
using (var stream = System.IO.File.Create(path))
encoder.Save(stream);
}
The test method runs without any errors and produces a png file at the location that I expected. However, this file is simply a black square rather than the red circle in a black square that I was expecting. Can anybody tell me why it is just rendering a black image, and what I can do to make it show the red circle.
You have to call bitmap.Render(drawingVisual) after the DrawingContext is closed.
From the Remarks on DrawingContext.Close:
A DrawingContext must be closed before its content can be rendered ...
So just move the Render call outside the using block:
using (DrawingContext dc = drawingVisual.RenderOpen())
{
dc.DrawEllipse(Brushes.Red, new Pen(Brushes.Red, 1),
new System.Windows.Point(50, 50), 50, 50);
}
bitmap.Render(drawingVisual);
Besides that, the red Pen seems redundant, since the circle is already filled red. So this should be ok:
dc.DrawEllipse(Brushes.Red, null, new System.Windows.Point(50, 50), 50, 50);
Also make sure to create the bitmap with a DPI value of 96, which corresponds to WPF device-independent units. Otherwise you would have to scale the drawing appropriately.
One and a half year later I faced the same problem - how to properly render a canvas without displaying it in the screen.
The solution was simpler than I thought and produces exactly the result one expects.
Long story short - to render the canvas without displaying it call Arrange(Rect finalRect) method on your canvas:
canvas.Arrange(new Rect(new Size(width, height)));
According to the documentation it:
Positions child elements and determines a size for a UIElement. Parent elements call this method from their ArrangeCore(Rect) implementation (or a WPF framework-level equivalent) to form a recursive layout update. This method constitutes the second pass of a layout update.

C# white or black unwanted pixels appear in the image

I am new to C#, I am using Visual Studo 2010, I have an image that needs to be displayed on a picturebox.
I tried many different methods. All the methods results in some unwanted pixels to appear along with image.
I have tried
picturebox.Image = Image.FromFile("bird.png");
result->
the image is displayed but with the stray white/black pixels at random places.
I also tried creating a bitmap of same size and drawing the image onto the bitmap and then assigning the bitmap to the picture box.Image. Still those unwanted pixels are visible.
I have tried clearing the picture box image (filling it with white or transparent) and then assigning the image, still same error occurs.
PS: this doesn't happen for all the images only certain images show this behaviour.
any help would be great
Code:
Image org = Bitmap.FromFile("bird.png");
Bitmap final = new Bitmap(org.Width,org.Height);
using (Graphics g = Graphics.FromImage(final))
{
g.DrawImage(org,0,0,GraphicsUnit.Pixel);
}
picturebox.Image = final;
if i use final.save("picture.png"). The "picuture.png" does not have that wrong pixels, it happens only when i use picture box to display it.
Please find the images attached defect orginal
PS: its not because of different fileformat (orginal and defect)
It was an TransperancyKey issue resolved by setting it to Default.

Resize transparent image with Magick.NET

I got some weird issues when resizing an image with transparency in Magick.NET. I am using Q16-AnyCPU.
I am resizing a 100px image to 400px.
MagickImage image = new MagickImage("test.png");
image.Resize(400, 400);
image.Write("test_resized.png");
I have tried many combinations of image.FilterType and image.Interpolate without any good results.
Only when I use image.AdaptiveResize(400, 400);, it looks somewhat better, but not as expected. The final image I want to resize is much bigger and AdaptiveResize is very slow.
When I disable Alpha via image.Alpha(AlphaOption.Off); I looks quice nice, but I want to keep the alpha.
Source image (the white area is transparent):
What I get:
What I want:
I had to set VirtuaPixelMethod, thanks for the hint:
MagickImage image = new MagickImage("test.png");
image.VirtualPixelMethod = VirtualPixelMethod.Transparent;
image.Resize(400, 400);
image.Write("test_resized.png");

How to zoom an image in&out in C#?

I want to implement zoom for an image. I don't want to resize the PictureBox, but the image itself.
How do I do this?
One solution is:
Create new image of the desired size (for example 200% or 50% of original image size)
Draw original image to new image using Graphics.DrawImage(Image, Rectangle);, which draws the given image to the new image at the given position with the given size
Set new image as source for the PictureBox
Another way is to simple create a new bitmap instance like that:
Size newSize = new Size((int)(originalBitmap.Width * zoomFactor), (int)(originalBitmap.Height * zoomFactor));
Bitmap bmp = new Bitmap(originalBitmap, newSize);
I used a web browser to achieve this.
//loads the image
myWebBrowser.Navigate(#"C:\myimage.png");
From there I used SendKeys to zoom in and out
myWebBrowser.Select(); //Selects browser.
SendKeys.Send("^{+}"); //Sends the control + key combo, causing the browser to zoom in. Replace the "+" with a "-" to zoom out.
It's a bit of a weird method, but it worked really well for me. I hope you find this helpful!

.NET set image display size

I am using some custom controls one of which is a tooltip controller that can display images, so I am using th ebelow code to instantiate it:
Image newImage = Image.FromFile(imagePath);
e.ToolTipImage = newImage;
obviously could inline it but just testing at the moment. The trouble is the image is sometimes the wrong size, is there a way to set the display size. The only way I can currently see is editing the image using GDI+ or something like that. Seems like a lot of extra processing when I am only wanting to adjust display size not affect the actual image.
Once you have an image object loaded from its source, the Height and Width (and Size, and all ancillary properties) are read-only. Therefore, you are stuck with GDI+ methods for resizing it in RAM and then displaying it accordingly.
There are a lot of approaches you can take, but if you were to encapsulate that out to a library which you could reuse should this problem occur again, you'll be set to go. This isn't exactly optimized (IE, may have some bugs), but should give you an idea of how to approach it:
Image newImage = Image.FromFile(myFilePath);
Size outputSize = new Size(200, 200);
Bitmap backgroundBitmap = new Bitmap(outputSize.Width, outputSize.Height);
using (Bitmap tempBitmap = new Bitmap(newImage))
{
using (Graphics g = Graphics.FromImage(backgroundBitmap))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Get the set of points that determine our rectangle for resizing.
Point[] corners = {
new Point(0, 0),
new Point(backgroundBitmap.Width, 0),
new Point(0, backgroundBitmap.Height)
};
g.DrawImage(tempBitmap, corners);
}
}
this.BackgroundImage = backgroundBitmap;
I did test this, and it worked. (It created a 200x200 resized version of one of my desktop wallpapers, then set that as the background image of the main form in a scratch WinForms project. You'll need using statements for System.Drawing and System.Drawing.Drawing2D.
In Winforms, if you contain the image inside a PictureBox control, the PictureBox control can be set to zoom to a particular height/width, and the image should conform.
At least that's what happened in my Head First C# book when I did the exercise.

Categories

Resources