views:

430

answers:

2

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.

+1  A: 

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.

John Rudy
Thanks my thinking was the display size is separate from the actual image resolution and... so it should be modifiable separately without truly editing the image, but perhaps not.
PeteT
Unfortunately, no ... Hope (a modified version of) this works out for you. :)
John Rudy
A: 

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.

John Dunagan
Thanks I am aware of that unfortunately this requires the passing in of an image in a method I can't override.
PeteT