Merge 2 images into 1 real-time

I have 2 images, 1 from file, the other one is a photo of the player, I need to put the 2nd one in the 1st one (at specified position, smaller, of course) and save the newly-created picture to file. How do I do that (most easily) at run-time?

If you know for sure that the overlay image is smaller (in width and height) than the background image then this should combine them:

var BackgroundTex : Texture2D;
var ForegroundTex : Texture2D;
private var newTex : Texture2D;
var sound : AudioClip;

function Start () {
	newTex = new Texture2D(BackgroundTex.width, BackgroundTex.height, TextureFormat.ARGB32, false);
	CombineTextures(newTex, BackgroundTex, ForegroundTex);

function CombineTextures (newTexture : Texture2D, Background : Texture2D, Overlay : Texture2D) {
	var offset = Vector2(((newTexture.width - Overlay.width)/2), ((newTexture.height - Overlay.height)/2));
	for(var y : int = 0; y < Overlay.height; y++){
		for(var x : int = 0; x < Overlay.width; x++){
			var PixelColorFore = Overlay.GetPixel(x, y)*Overlay.GetPixel(x, y).a;
			var PixelColorBack = newTexture.GetPixel(x + offset.x, y + offset.y)*(1-PixelColorFore.a);
			newTexture.SetPixel(x + offset.x, y + offset.y, PixelColorBack + PixelColorFore);

you can then use DrawTexture in OnGUI with newTex as you would with other textures or write it to a png

I would not suggest doing this often at runtime as it is not fast, It would be better to ‘fake’ it for the most part by simply drawing one image and then the other on top in a gui method if you want to show it on screen, and only use this method if you want to save the image to disk.


you need to make sure the textures that are used to create the new texture are read/writable, to do this go to the texture import settings, under texture type select advanced, then tick the box for ‘Read/Write Enabled’

I would also suggest making the texture formats one of ARGB32, RGB24 or Alpha8 (I used ARGB32 when testing the code)