59

I am trying to merge two different images and create a new one. This is the way I would like to do: I have this image (A):

polaroid

It's a PNG image and I would like to merge this one with another image (B) which I took from the phone to create something like this:

polaroid merged

I need a function who merge A with B creating C. The size must remain from the A image and the image B should auto adapt the size to fit into the polaroid (A). Is it possible to do that? Thank for your help!

UPDATE Just one thing, the image (A) is a square and the image i took is a 16:9, how can i fix that?? If i use your function the image (B) that i took become stretched!

pkamb
  • 33,281
  • 23
  • 160
  • 191
Luca Alberto
  • 1,195
  • 3
  • 11
  • 30

7 Answers7

122

Hope this may help you,

var bottomImage = UIImage(named: "bottom.png")
var topImage = UIImage(named: "top.png")

var size = CGSize(width: 300, height: 300)
UIGraphicsBeginImageContext(size)

let areaSize = CGRect(x: 0, y: 0, width: size.width, height: size.height)
bottomImage!.draw(in: areaSize)

topImage!.draw(in: areaSize, blendMode: .normal, alpha: 0.8)

var newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

All the Best :)

Pineapple3D
  • 121
  • 1
  • 8
Pallavi Konda
  • 1,640
  • 1
  • 12
  • 18
  • can you try to change the alpha value to 1.0 or 0.1.. am not sure about the value – Pallavi Konda Aug 14 '15 at 09:57
  • 2
    You can use different version of `drawInRect` which is not taking blending option as argument which is `topImage!.drawInRect(CGRectMake(xPosition, yPosition, topImage!.size.width, topImage!.size.height))` – Aleksander Grzyb Aug 14 '15 at 09:59
  • just one thing, the image (A) is a square and the image i took is a 16:9, how can i fix that?? If i use your function the image (B) that i took become stretched! – Luca Alberto Aug 14 '15 at 16:21
  • I used this and generated a base64 string of the new image. and its resulting in a blank image. I checked it on https://codebeautify.org/base64-to-image-converter#. The image results in a blank white image. What i am trying to do is merge two image parallel to each other. Can someone help me out please ? – Zahurafzal Mirza Jan 22 '19 at 07:20
30

Swift 5: Extension for UIImage

extension UIImage {
  func mergeWith(topImage: UIImage) -> UIImage {
    let bottomImage = self

    UIGraphicsBeginImageContext(size)


    let areaSize = CGRect(x: 0, y: 0, width: bottomImage.size.width, height: bottomImage.size.height)
    bottomImage.draw(in: areaSize)

    topImage.draw(in: areaSize, blendMode: .normal, alpha: 1.0)

    let mergedImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return mergedImage
  }
}
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Glen
  • 387
  • 3
  • 7
19

Swift 4 UIImage extension that enables easy image merging / overlaying.

extension UIImage { 

  func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat) -> UIImage {
    let newWidth = size.width < posX + image.size.width ? posX + image.size.width : size.width
    let newHeight = size.height < posY + image.size.height ? posY + image.size.height : size.height
    let newSize = CGSize(width: newWidth, height: newHeight)

    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
    draw(in: CGRect(origin: CGPoint.zero, size: size))
    image.draw(in: CGRect(origin: CGPoint(x: posX, y: posY), size: image.size))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return newImage
  }

}
budiDino
  • 13,044
  • 8
  • 95
  • 91
  • Thanks this is a nice one, but it does not handle negative posX or posY correctly. I'll add an answer that takes them into account. – OwlOCR Oct 31 '18 at 12:33
16

This way the overlay picture will be much cleaner:

class func mergeImages(imageView: UIImageView) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(imageView.frame.size, false, 0.0)
    imageView.superview!.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return image 
}

enter image description here

pkamb
  • 33,281
  • 23
  • 160
  • 191
Svitlana
  • 2,938
  • 1
  • 29
  • 38
  • Problem: I got with space on top, bottom when `UIImageView` have `Frame(10,10, width, height)` Solution: Add `UIImageView` into the view so it will become the `Frame(0, 0, width, height)` and Fixed the white space top and bottom. – Ilesh P Feb 07 '19 at 09:48
4

Objective C version of this solution with top image re-centered logic :

-(UIImage *)getImageInclosedWithinAnotherImage
{
    float innerImageSize = 20;
    UIImage *finalImage;

    UIImage *outerImage = [UIImage imageNamed:@"OuterImage.png"];
    UIImage *innerImage = [UIImage imageNamed:@"InnerImage.png"];

    CGSize outerImageSize = CGSizeMake(40, 40); // Provide custom size or size of your actual image
    UIGraphicsBeginImageContext(outerImageSize);

    //calculate areaSize for re-centered inner image
    CGRect areSize = CGRectMake(((outerImageSize.width/2) - (innerImageSize/2)), ((outerImageSize.width/2) - (innerImageSize/2)), innerImageSize, innerImageSize);
    [outerImage drawInRect:CGRectMake(0, 0, outerImageSize.width, outerImageSize.height)];
    [innerImage drawInRect:areSize blendMode:kCGBlendModeNormal alpha:1.0];

    finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return finalImage;
}
Miknash
  • 7,888
  • 3
  • 34
  • 46
iLearner
  • 1,670
  • 2
  • 19
  • 45
  • 3
    Whomsoever has down-voted my answer, could you also take a moment and add your comment why its down-voted, so that I will also get to know what was wrong with my answer. – iLearner Jul 09 '18 at 10:02
3

The upvoted answer stretches the background image changing its ratio. The solution below fixes that by rendering the image from a UIView that contains the two image views as subviews.

ANSWER YOU ARE LOOKING FOR (Swift 4):

func blendImages(_ img: UIImage,_ imgTwo: UIImage) -> Data? {
    let bottomImage = img
    let topImage = imgTwo

    let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: 306, height: 306))
    let imgView2 = UIImageView(frame: CGRect(x: 0, y: 0, width: 306, height: 306))

    // - Set Content mode to what you desire
    imgView.contentMode = .scaleAspectFill
    imgView2.contentMode = .scaleAspectFit

    // - Set Images
    imgView.image = bottomImage
    imgView2.image = topImage

    // - Create UIView
    let contentView = UIView(frame: CGRect(x: 0, y: 0, width: 306, height: 306))
    contentView.addSubview(imgView)
    contentView.addSubview(imgView2)

    // - Set Size
    let size = CGSize(width: 306, height: 306)

    // - Where the magic happens
    UIGraphicsBeginImageContextWithOptions(size, true, 0)

    contentView.drawHierarchy(in: contentView.bounds, afterScreenUpdates: true)

    guard let i = UIGraphicsGetImageFromCurrentImageContext(),
        let data = UIImageJPEGRepresentation(i, 1.0)
        else {return nil}

    UIGraphicsEndImageContext()

    return data
}

The returned image data doubles the size of the image, so set the size of the views at half the desired size.

  • EXAMPLE: I wanted the width and height of the image to be 612, so I set the view frames width and height to 306) // Enjoy :)
Rod
  • 789
  • 7
  • 19
Milez
  • 31
  • 2
2

Slightly modified version of answer by budidino. This implementation also handles negative posX and posY correctly.

extension UIImage {
    func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat) -> UIImage {
        let newWidth = posX < 0 ? abs(posX) + max(self.size.width, image.size.width) :
            size.width < posX + image.size.width ? posX + image.size.width : size.width
        let newHeight = posY < 0 ? abs(posY) + max(size.height, image.size.height) :
            size.height < posY + image.size.height ? posY + image.size.height : size.height
        let newSize = CGSize(width: newWidth, height: newHeight)

        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        let originalPoint = CGPoint(x: posX < 0 ? abs(posX) : 0, y: posY < 0 ? abs(posY) : 0)
        self.draw(in: CGRect(origin: originalPoint, size: self.size))
        let overLayPoint = CGPoint(x: posX < 0 ? 0 : posX, y: posY < 0 ? 0 : posY)
        image.draw(in: CGRect(origin: overLayPoint, size: image.size))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return newImage
    }
}
OwlOCR
  • 1,127
  • 11
  • 22