Skip to content

Instantly share code, notes, and snippets.

@Stayrony
Created December 24, 2019 18:24
Show Gist options
  • Save Stayrony/0465fab1c08966528bdffdba670b5372 to your computer and use it in GitHub Desktop.
Save Stayrony/0465fab1c08966528bdffdba670b5372 to your computer and use it in GitHub Desktop.
How to merge multiple images into one with Xamarin.iOS C#
namespace Mobile.Services
{
public interface IImageMergeService
{
byte[] MergeTwoImageByteArrays(byte[] imageBackgroundBytes, byte[] imageForegroundBytes);
}
}
using System;
using System.Runtime.InteropServices;
using CoreGraphics;
using Foundation;
using UIKit;
namespace Mobile.Platforms.Ios.Services
{
public class ImageMergeService : IImageMergeService
{
public byte[] MergeTwoImageByteArrays(byte[] imageBackgroundBytes, byte[] imageForegroundBytes)
{
byte[] resultByteArray;
UIImage resultImage;
var dataBackground = NSData.FromArray(imageBackgroundBytes);
var imageBackground = UIImage.LoadFromData(dataBackground);
var dataForeground = NSData.FromArray(imageForegroundBytes);
var imageForeground = UIImage.LoadFromData(dataForeground);
var width = imageBackground.Size.Width;
var height = imageBackground.Size.Height;
// Get max width and height of the image
width = imageForeground.Size.Width > width ? imageForeground.Size.Width : width;
height = imageForeground.Size.Height > height ? imageForeground.Size.Height : height;
using (var renderer = new UIGraphicsImageRenderer(new CGSize(width, height)))
{
resultImage = renderer.CreateImage((UIGraphicsImageRendererContext ctxt) =>
{
imageBackground.Draw(CGPoint.Empty);
imageForeground.Draw(CGPoint.Empty);
});
}
using (NSData imageData = resultImage.AsPNG())
{
resultByteArray = new Byte[imageData.Length];
Marshal.Copy(imageData.Bytes, resultByteArray, 0, Convert.ToInt32(imageData.Length));
}
return resultByteArray;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment