Click here to Skip to main content
Click here to Skip to main content

Resizing a Photographic image with GDI+ for .NET

By , 24 Sep 2002
 

Introduction

One of the common tasks often performed to photographic images is resizing. In general, scaling an image by a certain percentage is quite simple. On the other hand this might not produce an image that best meets your needs. Often it is more appropriate to Crop and/or Pad that image to achieve a standard height or width. Using some simple techniques, there is an easy way to accomplish these tasks programmatically using C# and GDI+.

In the first step we will load two photographs. The first photograph has a landscape orientation while the other is portrait. This will allow for a better demonstration of how one can resize a photograph of varying sizes and proportions.

string WorkingDirectory = @"C:\Tutorials\ImageResize";
Image imgPhotoVert = Image.FromFile(WorkingDirectory + 
                                @"\imageresize_vert.jpg");
Image imgPhotoHoriz = Image.FromFile(WorkingDirectory + 
                               @"\imageresize_horiz.jpg");
Image imgPhoto = null;

Example # 1 - Scale by percent

In this example we will demonstrate a simple method of scaling a photograph by a specified percentage. Both the width and height will be scaled uniformly.

imgPhoto = ScaleByPercent(imgPhotoVert, 50);
imgPhoto.Save(WorkingDirectory + 
    @"\images\imageresize_1.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
....
static Image ScaleByPercent(Image imgPhoto, int Percent)
{
    float nPercent = ((float)Percent/100);

    int sourceWidth = imgPhoto.Width;
    int sourceHeight = imgPhoto.Height;
    int sourceX = 0;
    int sourceY = 0;

    int destX = 0;
    int destY = 0; 
    int destWidth  = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Bitmap bmPhoto = new Bitmap(destWidth, destHeight, 
                             PixelFormat.Format24bppRgb);
    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, 
                            imgPhoto.VerticalResolution);

    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

    grPhoto.DrawImage(imgPhoto, 
        new Rectangle(destX,destY,destWidth,destHeight),
        new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
        GraphicsUnit.Pixel);

    grPhoto.Dispose();
    return bmPhoto;
}

Scaled to 50% of original size

In the above example we define a series of variables that are used in the process of scaling the image. sourceWidth, sourceHeight, sourceX, sourceY are used to build up a source rectangle structure. This structure specifies the portion of the source image object to draw. In our example we want the entire image, so our source rectangle will have the following values: new Rectangle(0,0,370,450).

destWidth, destHeight, destX, destY are used to build a destination rectangle structure. This structure specifies the location and size of the drawn image. The image is scaled to fit this rectangle. The destWidth and destHeight are calculated by multiplying the sourceWidth and sourceHeight by the percentage we want it scaled by. The result is a Bitmap with the new width and height and a destination rectangle with the following values: new Rectangle(0,0,185,225).

Example #2 - Scale to a fixed size

A very common task used when creating images for a web site is to resize those images to have a fixed width and height. Often when displaying a list of data, it is beneficial to have any columns that contain images occupy identical dimensions. Since images will have varying orientations it will be necessary to fit either the width or height, then pad the opposite dimension with filler.

imgPhoto = FixedSize(imgPhotoVert, 300, 300);
imgPhoto.Save(WorkingDirectory + 
    @"\images\imageresize_3.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
....
static Image FixedSize(Image imgPhoto, int Width, int Height)
{
    int sourceWidth = imgPhoto.Width;
    int sourceHeight = imgPhoto.Height;
    int sourceX = 0;
    int sourceY = 0;
    int destX = 0;
    int destY = 0; 

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)Width/(float)sourceWidth);
    nPercentH = ((float)Height/(float)sourceHeight);
    if(nPercentH < nPercentW)
    {
        nPercent = nPercentH;
        destX = System.Convert.ToInt16((Width - 
                      (sourceWidth * nPercent))/2);
    }
    else
    {
        nPercent = nPercentW;
        destY = System.Convert.ToInt16((Height - 
                      (sourceHeight * nPercent))/2);
    }

    int destWidth  = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Bitmap bmPhoto = new Bitmap(Width, Height, 
                      PixelFormat.Format24bppRgb);
    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, 
                     imgPhoto.VerticalResolution);

    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.Clear(Color.Red);
    grPhoto.InterpolationMode = 
            InterpolationMode.HighQualityBicubic;

    grPhoto.DrawImage(imgPhoto, 
        new Rectangle(destX,destY,destWidth,destHeight),
        new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
        GraphicsUnit.Pixel);

    grPhoto.Dispose();
    return bmPhoto;
}

In the above example it is our desire to create an image with a width of 300 and a height of 300. The first step in accomplishing this is to determine the smallest possible percent that we can shrink this image, while making sure to fill the maximum height and width.

nPercentW = ((float)Width/(float)sourceWidth);
nPercentH = ((float)Height/(float)sourceHeight);
if(nPercentH < nPercentW)
{
    nPercent = nPercentH;
    destX = (int)((Width - (sourceWidth * nPercent))/2);
}
else
{
    nPercent = nPercentW;
    destY = (int)((Height - (sourceHeight * nPercent))/2);
}

To do this we will calculate both a height percentage and a width percentage and check which is smaller. nPercentW =.8108 while nPercentH=.6666. Choosing the smaller percentage guarantees that none of the image will be cropped. Since height is the smaller reduction, this will be our maximum percent to scale the original image.

When this percent is applied to the width, we end up with a width equal to 247. Our desired destWidth was 300, so we will need to pad each side of the image with 27 additional pixels. This padding is accomplished by setting the destX=27. This will shift the newly scaled image to the right 27 pixels.

Using the desired nPercent and destX, we can build up the appropriate destination Rectangle and draw the new image.

Example #3 - Scale with cropping

The last resizing technique we will discuss is the process of cropping an image. This technique follows a similar methodology as the previous fixed size example with a few exceptions.

imgPhoto = Crop(imgPhotoVert, 300, 300, AnchorPosition.Bottom);
imgPhoto.Save(WorkingDirectory + 
       @"\images\imageresize_4.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();

....
static Image Crop(Image imgPhoto, int Width, 
                    int Height, AnchorPosition Anchor)
{
    int sourceWidth = imgPhoto.Width;
    int sourceHeight = imgPhoto.Height;
    int sourceX = 0;
    int sourceY = 0;
    int destX = 0;
    int destY = 0;

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)Width/(float)sourceWidth);
    nPercentH = ((float)Height/(float)sourceHeight);

    if(nPercentH < nPercentW)
    {
        nPercent = nPercentW;
        switch(Anchor)
        {
            case AnchorPosition.Top:
                destY = 0;
                break;
            case AnchorPosition.Bottom:
                destY = (int)
                    (Height - (sourceHeight * nPercent));
                    break;
            default:
                destY = (int)
                    ((Height - (sourceHeight * nPercent))/2);
                break;
        }
    }
    else
    {
        nPercent = nPercentH;
        switch(Anchor)
        {
            case AnchorPosition.Left:
                destX = 0;
                break;
            case AnchorPosition.Right:
                destX = (int)
                  (Width - (sourceWidth * nPercent));
                break;
            default:
                destX = (int)
                  ((Width - (sourceWidth * nPercent))/2);
                break;
        } 
    }

    int destWidth  = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Bitmap bmPhoto = new Bitmap(Width, 
            Height, PixelFormat.Format24bppRgb);
    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, 
            imgPhoto.VerticalResolution);

    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.InterpolationMode = 
            InterpolationMode.HighQualityBicubic;

    grPhoto.DrawImage(imgPhoto, 
        new Rectangle(destX,destY,destWidth,destHeight),
        new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
        GraphicsUnit.Pixel);

    grPhoto.Dispose();
    return bmPhoto;
}

When cropping an image you have 5 choices as to how one decides, what part of the image to crop. We refer to this as how one anchors the image. Top, bottom, and center are appropriate when cropping an image's height where as left, right and center are appropriate for width. (There are more, but for the purpose of this example we will focus in these 5.)

Similar to example #2, the first thing we need to do is determine a height percentage and a width percentage that gets us to the desired dimensions. Since our desired dimensions are 300x300, we end up with the same percentages as in the previous example. Once again we will compare the two, but this time we will choose the larger of the two percentages. (nPercentW = .8108)

if(nPercentH < nPercentW)
{
    nPercent = nPercentW;
    switch(Anchor)
    {
        case AnchorPosition.Top:
 destY = 0;
 break;
        case AnchorPosition.Bottom:
 destY = (int)(Height - (sourceHeight * nPercent));
 break;
        default:
 destY = (int)((Height - (sourceHeight * nPercent))/2);
 break;
    }
}

Image anchored top

Image anchored center

Image anchored bottom

By using 3 different destY values, we can achieve the 3 different ways to crop the image. If our source image would have had a landscape orientation, then left, right and center would have been appropriate and destX would have been used to achieve a crop of the image's width.

One last thing...

In all of the examples, we called both the SetResolution and InterpolationMode prior to drawImage. SetResolution does just as the name implies. In these examples, we carry over the original image's resolution by setting this property equal to imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution.

bmPhoto.SetResolution(imgPhoto.HorizontalResolution, 
                                 imgPhoto.VerticalResolution);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

Interpolation refers to how data is interpolated between endpoints. In its simplest form, to interpolate is to estimate a missing value by taking an average of known values at neighboring points. Below is the graphical representation of three different approaches to interpolation.

In general the bicubic interpolation is used when more accuracy is desired than the bilinear interpolation.

Bicubic interpolation

Bilinear interpolation

Nearest-neighbor interpolation

That's it! Compile the project, run it, and see what happens! The code is fairly straightforward. If it all makes sense, then these resizing techniques can be used to scale virtually any image.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Joel Neubeck
Web Developer
United States United States
Member
Joel is a Microsoft.NET system architect and Director of Development for a leading interactive development firm located in Tempe, Arizona. Our firm designs and develops a wide range of custom web applications which leverage Flash, Ajax, ASP.NET and the Microsoft.Net Framework.
In his free time, he enjoys spending time with his wife and children.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionFixed file size 2288x2288 to size 55x55 error!memberhaiaun17 Jul '12 - 21:57 
Fixed file size 2288x2288 to size 55x55 correct. After add picture size 55x55 to MS Excel, picture size is very small.
GeneralMy vote of 5memberRazaToosy7 Apr '12 - 13:11 
Helped me a lot with Avoiding having to work out the values myself. Thank you!
NewsSee imageresizing.netmemberNathanael Jones6 Jan '12 - 6:40 
For an open-source implementation that handles all the math and memory management for you, and avoids these bugs, see the imageresizing.net project.
GeneralRe: See imageresizing.netmemberedisonsolutions6 Jan '12 - 20:32 
Thanks for sharing. Great work and great in-depth articles. Very useful!
GeneralAwesome. +5memberkcs6 Dec '11 - 16:57 
Great code and very well done. Using this in production (with some project specific changes) and it works great. Thank you for sharing this.
QuestionReSizing the Imagemembersrinivas dudam5 Oct '11 - 5:17 
Hi
 
I am using the code works fine. The thing I did not understand is the Formula how it is calculated.
 

Thanks
GeneralMy vote of 5membersrinivas dudam5 Oct '11 - 5:15 
Hi joel,
Thank You For Such a good article.
Keep posting. Brilliant work.
GeneralResizing images in bytesmemberAli Taghvajou9 Apr '11 - 7:56 
all may images are stored as byte array in database.
I have faced a limitation of max size of images. so I should resize the large one.
What is your opinion?
GeneralMy vote of 5memberThe InfOracle1 Apr '11 - 8:19 
Coding was solid for me. Exactly what I was looking for.
GeneralMy final solution to the "border bug" (black borders on some edges)memberedisonsolutions25 Feb '11 - 1:36 
First I changed to this:
 
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

g.DrawImage(imgPhoto,
    new RectangleF(destX - 0.5F, destY - 0.5F, destWidth + 1, destHeight + 1),
    new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
    GraphicsUnit.Pixel);
 
That almost solved the problem. There are no borders when I resize to a smaller size (thumbnail), but when resizing to a larger size I sometimes get light grey borders.
 
I added this change as well:
 
Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);  // Was: .Format24bppRgb
 
Now all unwanted borders are gone. Excellent!
 
(Note: I haven't tested if the 32bpp change is enough for solving the downsizing borders as well.)

-- Håkan

GeneralRe: My final solution to the "border bug" (black borders on some edges)memberNathanael Jones6 Jan '12 - 6:41 
You also need to use the ImageAttributes class with TileModeXY set for the last parameter of DrawImage, otherwise you'll still get a slight border on some images.
GeneralMy vote of 5memberedisonsolutions25 Feb '11 - 0:24 
Exactly the info I needed. Thanks!
GeneralMy vote of 5memberAli Taghvajou26 Jan '11 - 22:15 
Really good and use full
GeneralMy vote of 5memberLeonic27 Dec '10 - 22:31 
great!
GeneralMy vote of 5memberTomJonckheere2 Nov '10 - 23:28 
Nice, understandable, helpfull!
GeneralMy vote of 1memberMember 208801413 Jul '10 - 21:35 
Code is not working properly
GeneralMy vote of 5memberMike Hankey2 Jul '10 - 11:45 
Nice work
GeneralGreat!memberLars Brandt20 Jan '10 - 9:43 
Works like a Charm! Smile | :)
 
Lars Brandt MCP/C#

QuestionHow to increase the image quality?memberDai Hoang22 Dec '09 - 15:47 
Thank Joel,
your article is very useful. But I've some probs at the resolution image. i saw that quality image be fixedSize is very slow. Although i tried to change interpolation. How can i increase quality.
Many thks Smile | :)
GeneralI tried but not workingmemberRustyGB22 Sep '09 - 1:27 
Please help me. When i tried the same code its not working giving error in following: after debugging
 
public override int GetTypeHashCode() {
return -1907506005;
}

public override void ProcessRequest(System.Web.HttpContext context) {
base.ProcessRequest(context);
}
GeneralTranslated to VB.NET for the Pocket PCmemberSlothie9 Aug '09 - 13:05 
Thanks very much for the sample. Smile | :) Oviously the PPC doesn't have some functions from the original.
 
    Private Function ScaleImage(ByVal imgPhoto As Image, ByVal Width As Long, ByVal Height As Long) As Image
 
        Dim sourceWidth As Long = imgPhoto.Width
        Dim sourceHeight As Long = imgPhoto.Height
        Dim sourceX As Long = 0
        Dim sourceY As Long = 0
        Dim destX As Long = 0
        Dim destY As Long = 0
 
        Dim nPercent As Double = 0
        Dim nPercentW As Double = 0
        Dim nPercentH As Double = 0
 
        nPercentW = Width / sourceWidth
        nPercentH = Height / sourceHeight
        If nPercentW < nPercentW Then
            nPercent = nPercentH
            destX = System.Convert.ToInt16((Width - (sourceWidth * nPercent)) / 2)
        Else
            nPercent = nPercentW
            destX = System.Convert.ToInt16((Height - (sourceHeight * nPercent)) / 2)
        End If
 
        Dim destWidth As Long = sourceWidth * nPercent
        Dim destHeight As Long = sourceHeight * nPercent
 
        Dim bmPhoto As Bitmap = New Bitmap(Width, Height, Imaging.PixelFormat.Format24bppRgb)
        Dim grPhoto As Graphics = Graphics.FromImage(bmPhoto)
 
        grPhoto.Clear(Color.Red)
 
        grPhoto.DrawImage(imgPhoto, New Rectangle(destX, destY, destWidth, destHeight), New Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel)
 
        grPhoto.Dispose()
        Return bmPhoto
 
    End Function

GeneralRe: Translated to VB.NET for the Pocket PCmemberllpnet1 Feb '10 - 6:59 
and could share setResolution function?
 
Saludos,
 
Luis Alfredo Lozada Portal
Microsoft DCE3
Trujillo - Perú

GeneralThank you very muchmemberAmi Drutman1 Apr '09 - 8:42 
You help a lot of us. I was looking for an article like this. EXCELLENT. Thank you very much!
QuestionMultiple page Tiff FilememberMuneer Safi2 Feb '09 - 19:37 
Does This Works for Multiple-page tiff file
i have a multiple-page tiff file that i need to change the width,height and resolution
GeneralGreat article!memberBigWorld11 Jan '09 - 19:59 
Really helpful!
GeneralAbout this articalmembersanjay3028 Nov '08 - 21:17 
Respected sir ,
 
i read and understood but tell me how this handle on mouse movement in asp.net(C#).
Generalplease helpa bout image crop,zoom,rotete,resize ,move etcmembersanjay3027 Nov '08 - 19:32 
Respected sir ,
 
Actualy i want to manage this code by front aspx file.like as directly select file from FileUpload control after click upload button image display in image box after i want crop ,zoom,move ,resize image,rotet.
 

so please tell me any one i have no more time for wait ..
 
modified on Friday, November 28, 2008 2:07 AM

Questionhow to save image in CMYK?memberRonen.Rimon18 Nov '08 - 20:59 
anyone knows how to save image (tiff or jpeg) in CMYK color type?
I tried to change the EncoderParameter but nothing helped.
GeneralPlease help: Portrait vs Landscape problemsmemberRobin Reyes8 Oct '08 - 15:38 
This code works great on normal pictures, but all image types are not "presentable" unless they are of "normal" dimensions. The problem is that if the image is landscape or portrait, the resize doesn't turn out very good...don't get me wrong, the code works great! However, could the functions please be modified to "avoid stretching a portrait/landscape image too far" based on its given width/height?
 
Thanks!
GeneralThank You!memberFireBlonde30 Sep '08 - 22:24 
Excellent example, which saved my time! I wasted 2 days to make it myself, but in vain. Good job!
QuestionAny chance of obtaing a working project?memberbuyValu20 Aug '08 - 10:46 
I'm obviously a newbie is there any chance of getting a working example in project form?
QuestionVery very helpful!memberSobia Saeed Magray26 Jun '08 - 20:57 
Thanks a lot, you have solved my problem. But one question is here in my mind? How I can do the following:-
1. When I press "resize" command in the menu, a window appears
2. Window contains three text boxes, first two for width and height and 3rd for percentage.
3. When I set the height, width will be set automatically
 
Kindly help me in this regard,
 
I am using c#.net environment first time.
 
HH

QuestionCan tell me a method to draw a Circle shape image instead of Rectangle shape?memberAswattha21 May '08 - 2:28 
Hi, Really you did a good job,
I have one question, can you tell me a method to draw the same image in a circle shape, have you ever tried this thing, if yes please tell me how to do this. As of now i tried in many ways but i failed to draw image in ellipse shape. If you find answer please let me know.
Thank you,
Regards,
Aswattha
AnswerRe: Can tell me a method to draw a Circle shape image instead of Rectangle shape?memberAswattha8 Dec '09 - 0:38 
I found the solution to crop image in circles and polygon shapes.
Here the only thing we have to remember is that we should save images in gif or png format, because if we save as jpeg, it shows white color behind cropped clip instead of transparent.
The sample code as follows
        int[] attribval = new Int32[4];
 
        // attribval[0] is srcX
        // attribval[1] is srcY
        // attribval[2] is srcW/width
        // attribval[3] is srcH/Height
        
        // set attribval array with custom values
        //assume that file1.jpg resides on the root level directory
        System.Drawing.Image imgSource = System.Drawing.Image.FromFile(Server.MapPath("./file1.jpg")); 
 
        //Bitmap imgTarget = new Bitmap(imgSource.Width, imgSource.Height);
        Bitmap imgTarget = new Bitmap(attribval[2], attribval[3]);
              
        Graphics g = Graphics.FromImage(imgTarget);
        imgTarget.SetResolution(imgSource.HorizontalResolution, imgSource.VerticalResolution);
        System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
        g.Clear(Color.Transparent);
        
        //path.AddRectangle(new Rectangle(0, 0, imgTarget.Width, imgTarget.Height));
        path.AddEllipse(new Rectangle(0, 0, imgTarget.Width, imgTarget.Height));
        //for (int x = 0; x < imgSource.Width; x++)
        //    for (int y = 0; y < imgSource.Height; y++)
        //        imgTarget.SetPixel(x, y, Color.Transparent);
       
        g.SetClip(path);
 
        //g.DrawImage(imgSource, 0, 0, imgSource.Width,imgSource.Height);
        g.DrawImage(imgSource, new Rectangle(0, 0, attribval[2], attribval[3]), attribval[0], attribval[1], attribval[2], attribval[3], GraphicsUnit.Pixel);
 
        //imgTarget.MakeTransparent(Color.Red);
        imgTarget.Save(Server.MapPath("./file1_clipped.png"), System.Drawing.Imaging.ImageFormat.Png);
 
        imgTarget.Dispose();
        imgSource.Dispose();
        g.Dispose();
 
       
soon i will post an article on this
meet me at http://aswattha.blogspot.com[^]
GeneralOutstanding! Thank you!memberFlashSand23 Apr '08 - 10:19 
Just wanted to say thanks ....
Excellent!
 
Fred
GeneralASP.NET (FileUpload)member111qwe22222 Apr '08 - 10:52 
Nice code!
Could you show me example how this code works with asp.net
 
Thanks in advance...
GeneralRe: ASP.NET (FileUpload)membersenthilmuruganbtech16 Jun '08 - 23:42 
poda looku.......
GeneralExcellent!memberciricivan22 Apr '08 - 4:15 
Thanks!!!
GeneralSuperb!memberPaul Roberts21 Mar '08 - 9:09 
Exactly what I needed - many thanks!
GeneralExcellent job! Really helped me.memberGeorge Serban24 Feb '08 - 11:44 
Helpful methods that can be used to resize any image without loosing quality.
Easy to implement and test. It's great! Wink | ;)
GeneralBrilliant!memberfevez8 Dec '07 - 2:28 
Thankyou for this article! Big Grin | :-D
 
It's saved me a lot of headache trying to do the same thing myself!
 
Fev
GeneralVery Good!!memberaonascimento8 Nov '07 - 8:32 
Thanks for this article... it helped me a lot.
GeneralUseful tipmemberzioturo11 Oct '07 - 22:06 
This component is very useful to manage image resize and crop:
http://www.radactive.com/en/Products/ILoad/Image_Resize_Crop_Upload.aspx[^]
 

GeneralBlack Line in CropmemberMartialWeb.com24 Sep '07 - 12:00 
I noticed a black line on the right side when cropping a portrait photo.
 
A black line appears on the bottom of the photo when cropping landscape.
 
Any thoughts on how to get rid of that? The issue shows up in the default code attached in the article...example 4 and 5.
 
Scott
GreatTalents.com
GeneralRe: Black Line in CropmemberMartialWeb.com24 Sep '07 - 12:26 
Just FYI. To fix the black line, modify the line from the Crop() method from
 
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
 
to:
 
int destWidth = ((int)(sourceWidth * nPercent)) + 1;
int destHeight = ((int)(sourceHeight * nPercent)) + 1;
 
Good job, by the way, on the code.
GeneralRe: Black Line in Cropmemberreach4thelasers23 Sep '09 - 10:27 
A better solution is to replace all the 'float' types with 'double'. Float isn't precise enough to preserve the fractions of width/height and height/width so when the destination image-size is calculated, there is a 1 pixel discrepancy caused by the rounding error resulting from the loss of precision.
 
In other news... for very small thumbnail images - 60x60, I get a black line on the top and left!! I couldn't figure out what was causing this, but int sourceX = 1; int sourceY = 1; instead of zero seemed to fix it - if anyone knows why this happens let me know! I presume its similar to the cause of the black line on the bottom/right.
AnswerRe: Black Line in Cropmemberdeepillgl11 Mar '08 - 7:05 
This did not work for me.
I found that the black lines can be removed by setting the initial values of

int destX = 0;
int destY = 0;

Change them to

int destX = -1;
int destY = -1;

 
Regards,
 
Fedja
Sobot Software
AnswerRe: Black Line in Cropmembercpsnosrap28 Aug '08 - 9:21 
To get rid of the seemingly random border lines, try setting the default background color of the graphics object first:
 
        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
        grPhoto.Clear(Color.White);
 
I think the lines are a side effect of doing pixel interpolation on the edges of the image.
GeneralRe: Black Line in Cropmemberpower988811 Sep '08 - 15:59 
I find to change the number in the code, it will get rid of the border as well.
 
public static Image ScaleByPercent(Image imgPhoto, int Percent)
        {
            float nPercent = ((float)Percent / 100);
 
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
 
            int destX = -1;
            int destY = -1;
            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);
 
            Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
 
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //grPhoto.Clear(Color.White);

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth + 1, destHeight + 1),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);
 
            grPhoto.Dispose();
            return bmPhoto;
        }

AnswerRe: Black Line in Cropmemberbj19934720 May '09 - 10:12 
To fix this you need to change the
 
int dest x =0;
int dest y=0;

 
to
 
int destX = -1;
int destY = -1;

 
and also....
 
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX,destY,destWidth,destHeight),
new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
GraphicsUnit.Pixel);

 
to
 
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX,destY,destWidth+1,destHeight+1),
new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
GraphicsUnit.Pixel);

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 25 Sep 2002
Article Copyright 2002 by Joel Neubeck
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid