2011-06-17 111 views
20

Tengo un requisito en el que necesito fusionar dos imágenes png/jpeg diferentes que resultan en una sola imagen usando C# .Net. Habrá una ubicación particular definida en la imagen de origen en la que necesito insertar otra imagen. ¿Alguien puede sugerir algunos enlaces?Combinar dos imágenes para crear una sola imagen en C# .Net

+1

Estaba buscando las mismas cosas y encontré esto. http://stackoverflow.com/questions/465172/merging-two-images-in-c-net/465195#465195 – ddaaggeett

Respuesta

6

responsabilidad: Trabajo en Atalasoft

Nuestra DotImage Photo SDK (que es gratuito) puede hacer esto.

Para abrir una imagen

AtalaImage botImage = new AtalaImage("bottomImage.png"); 
AtalaImage topImage = new AtalaImage("topImage.png"); 

Para superponer una encima de otra

Point pos = new Point(0,0); // or whatever you need 
OverlayCommand cmd = new OverlayCommand(topImage, pos); 
ImageResults res = cmd.Apply(botImage); 

Si necesita la imagen resultante a tener un tamaño diferente, mira el CanvasCommand. También podría crear una imagen Atala del tamaño que necesita, y luego superponer cada imagen en ella.

Para guardar

botImage.Save("newImage.png", new PngEncoder(), null); 
+1

DotImage Photo SDK ya no es gratuito. :( –

+4

Perdón por eso, ya no trabajo allí. Las otras respuestas a esta pregunta todavía deberían funcionar para usted. –

31

Este método fusionar dos imágenes una en la parte superior de la otra se puede modificar el código para satisfacer sus necesidades:

public static Bitmap MergeTwoImages(Image firstImage, Image secondImage) 
    { 
     if (firstImage == null) 
     { 
      throw new ArgumentNullException("firstImage"); 
     } 

     if (secondImage == null) 
     { 
      throw new ArgumentNullException("secondImage"); 
     } 

     int outputImageWidth = firstImage.Width > secondImage.Width ? firstImage.Width : secondImage.Width; 

     int outputImageHeight = firstImage.Height + secondImage.Height + 1; 

     Bitmap outputImage = new Bitmap(outputImageWidth, outputImageHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

     using (Graphics graphics = Graphics.FromImage(outputImage)) 
     { 
      graphics.DrawImage(firstImage, new Rectangle(new Point(), firstImage.Size), 
       new Rectangle(new Point(), firstImage.Size), GraphicsUnit.Pixel); 
      graphics.DrawImage(secondImage, new Rectangle(new Point(0, firstImage.Height + 1), secondImage.Size), 
       new Rectangle(new Point(), secondImage.Size), GraphicsUnit.Pixel); 
     } 

     return outputImage; 
    } 
+0

por qué Format32bppArgb? – Toolkit

+0

@Toolkit: Por lo que recuerdo, cuando usa la sobrecarga del constructor con dos argumentos solo '(ancho, alto)' creará una versión '24bit' que es' Format24bppRgb'. Y perderá la información del canal alfa de las imágenes originales si incluye una, de ahí el 'Format32bppArgb'. Aunque, creo sería más conveniente si obtienes el formato apropiado de las imágenes originales en lugar del formato en línea 'Format32bppArgb' ... –

10

Después de todo esto, he encontrado una nuevo método más fácil probar este ..

puede unirse a varias fotos juntos:

public static System.Drawing.Bitmap CombineBitmap(string[] files) 
{ 
    //read all images into memory 
    List<System.Drawing.Bitmap> images = new List<System.Drawing.Bitmap>(); 
    System.Drawing.Bitmap finalImage = null; 

    try 
    { 
     int width = 0; 
     int height = 0; 

     foreach (string image in files) 
     { 
      //create a Bitmap from the file and add it to the list 
      System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image); 

      //update the size of the final bitmap 
      width += bitmap.Width; 
      height = bitmap.Height > height ? bitmap.Height : height; 

      images.Add(bitmap); 
     } 

     //create a bitmap to hold the combined image 
     finalImage = new System.Drawing.Bitmap(width, height); 

     //get a graphics object from the image so we can draw on it 
     using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage)) 
     { 
      //set background color 
      g.Clear(System.Drawing.Color.Black); 

      //go through each image and draw it on the final image 
      int offset = 0; 
      foreach (System.Drawing.Bitmap image in images) 
      { 
       g.DrawImage(image, 
        new System.Drawing.Rectangle(offset, 0, image.Width, image.Height)); 
       offset += image.Width; 
      } 
     } 

     return finalImage; 
    } 
    catch (Exception) 
    { 
     if (finalImage != null) 
      finalImage.Dispose(); 
     //throw ex; 
     throw; 
    } 
    finally 
    { 
     //clean up memory 
     foreach (System.Drawing.Bitmap image in images) 
     { 
      image.Dispose(); 
     } 
    } 
} 
+2

Impresionante, gracias por el código, pero nunca por" throw ex ", siempre solo por" throw ". Estás restablecer la pila e imposibilitar la depuración de lo contrario! – TheSoftwareJedi

+0

Este código me genera una imagen final con el doble del ancho que el original (la altura permanece correcta) –

+0

@PabloCost a Sí, si ve el código anterior 'height = bitmap.Height> height? bitmap.Height: height; 'height de la imagen recién creada será el máximo de todas las imágenes. –

5
 String jpg1 = @"c:\images.jpeg"; 
     String jpg2 = @"c:\images2.jpeg"; 
     String jpg3 = @"c:\image3.jpg"; 

     Image img1 = Image.FromFile(jpg1); 
     Image img2 = Image.FromFile(jpg2); 

     int width = img1.Width + img2.Width; 
     int height = Math.Max(img1.Height, img2.Height); 

     Bitmap img3 = new Bitmap(width, height); 
     Graphics g = Graphics.FromImage(img3); 

     g.Clear(Color.Black); 
     g.DrawImage(img1, new Point(0, 0)); 
     g.DrawImage(img2, new Point(img1.Width, 0)); 

     g.Dispose(); 
     img1.Dispose(); 
     img2.Dispose(); 

     img3.Save(jpg3, System.Drawing.Imaging.ImageFormat.Jpeg); 
     img3.Dispose(); 
+0

Intenté algo similar siguiendo tu método. Configuro un ancho mayor y cuando dibujo las imágenes, se mostrará una región gris. ¿Cómo puedo cambiar esa región a blanco u otro color sólido de mi preferencia? –

Cuestiones relacionadas