Image resizing algorithm

后端 未结 2 2008
無奈伤痛
無奈伤痛 2020-12-15 09:29

I want to write a function to downsize an image to fit specified bounds. For example i want to resize a 2000x2333 image to fit into 1280x800. The aspect ratio must be mainta

相关标签:
2条回答
  • 2020-12-15 09:52

    Here's a way to approach the problem:

    You know that either the image's height or width will be equal to that of the bounding box.

    Once you've determined which dimension will equal the bounding box's, you use the image's aspect ratio to calculate the other dimension.

    double sourceRatio = sourceImage.Width / sourceImage.Height;
    double targetRatio = targetRect.Width / targetRect.Height;
    
    Size finalSize;
    if (sourceRatio > targetRatio)
    {
        finalSize = new Size(targetRect.Width, targetRect.Width / sourceRatio);
    }
    else
    {
        finalSize = new Size(targetRect.Height * sourceRatio, targetRect.Height);
    }
    
    0 讨论(0)
  • 2020-12-15 09:55

    The way I usually do this is to look at the ratio between the original width and the new width and the ratio between the original height and the new height.

    After this shrink the image by the biggest ratio. For example, if you wanted to resize an 800x600 image into a 400x400 image the width ratio would be 2, and the height ratio would be 1.5. Shrinking the image by a ratio of 2 gives a 400x300 image.

    NSSize mysize = [self pixelSize]; // just to get the size of the original image
    int neww, newh = 0;
    float rw = mysize.width / width; // width and height are maximum thumbnail's bounds
    float rh = mysize.height / height;
    
    if (rw > rh)
    {
        newh = round(mysize.height / rw);
        neww = width;
    }
    else
    {
        neww = round(mysize.width / rh);
        newh = height;
    }
    
    0 讨论(0)
提交回复
热议问题