0

Every solution in this thread successfully resizes the image but the resized image has a background (black or white depending on what the "opaque" bool is set to in "UIGraphicsBeginImageContextWithOptions()") even though the original image does not. Is there a way to resize an image without adding a background?

For instance, the accepted solution:

func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage? {
    let size = image.size

    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
    } else {
        newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

original image

resized image

1 Answers1

0

By "without adding a background" I gather you mean that you want to preserve transparency in your source image, aka preserve the alpa channel. Your original image is a PNG. Your resized image is a JPG.

PNG images can contain an alpha channel. JPG images cannot. If you save an image to a JPG you will always lose transparency. You are losing transparency/adding a background when you save your file to a JPG.

It's much more than you asked for, but I wrote a demo app a while ago that allows you to mask away parts of an image or unmask them, and then save the resulting image to a file.

You can try the project at this link:

https://github.com/DuncanMC/MaskableImageView.git

By the way, you should do offscreen rendering with UIGraphicsImageRenderer rather than UIGraphicsBeginImageContextWithOptions (My demo app shows how.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • had to save it as a PNG image instead of JPEG like you mentioned. thank you for your quick response! also appreciate you sharing your related project. – user21757794 Apr 29 '23 at 03:51