2009-01-21 27 views
68

Idea simple: Tengo dos imágenes que quiero fusionar, una es 500x500 que es transparente en el medio y la otra es 150x150.Fusionando dos imágenes en C# /. NET

La idea básica es esta: cree un lienzo vacío de 500x500, coloque la imagen de 150x150 en el medio del lienzo vacío y luego copie la imagen de 500x500 para que el centro transparente permita que brille el 150x150.

Sé cómo hacerlo en Java, PHP y Python ... Simplemente no tengo idea de qué objetos/clases usar en C#, sería suficiente un ejemplo rápido de copiar una imagen a otra.

+0

¿Le sirve de ayuda? http://www.daniweb.com/forums/thread87993.html – Dror

Respuesta

85

básicamente yo uso esto en una de nuestras aplicaciones: queremos superponer un PlayIcon sobre un marco de un vídeo:

Image playbutton; 
try 
{ 
    playbutton = Image.FromFile(/*somekindofpath*/); 
} 
catch (Exception ex) 
{ 
    return; 
} 

Image frame; 
try 
{ 
    frame = Image.FromFile(/*somekindofpath*/); 
} 
catch (Exception ex) 
{ 
    return; 
} 

using (frame) 
{ 
    using (var bitmap = new Bitmap(width, height)) 
    { 
     using (var canvas = Graphics.FromImage(bitmap)) 
     { 
      canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; 
      canvas.DrawImage(frame, 
          new Rectangle(0, 
              0, 
              width, 
              height), 
          new Rectangle(0, 
              0, 
              frame.Width, 
              frame.Height), 
          GraphicsUnit.Pixel); 
      canvas.DrawImage(playbutton, 
          (bitmap.Width/2) - (playbutton.Width/2), 
          (bitmap.Height/2) - (playbutton.Height/2)); 
      canvas.Save(); 
     } 
     try 
     { 
      bitmap.Save(/*somekindofpath*/, 
         System.Drawing.Imaging.ImageFormat.Jpeg); 
     } 
     catch (Exception ex) { } 
    } 
} 
+9

¡GRACIAS! Totalmente guardado mi tocino hoy –

+0

@downvoter cuidado para elaborar, por lo que puedo mejorar mi respuesta? –

+3

@AndreasNiedermair el votante a la baja probablemente copió el código pegado y no funcionó –

50

Esto agregará una imagen a otra.

using (Graphics grfx = Graphics.FromImage(image)) 
{ 
    grfx.DrawImage(newImage, x, y) 
} 

Gráficos está en el espacio de nombres System.Drawing

22

Después de todo esto, encontré un nuevo método más fácil de probar esto ...

Puede unir múltiples fotos juntas:

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 ex) 
    { 
     if (finalImage != null) 
      finalImage.Dispose(); 

     throw ex; 
    } 
    finally 
    { 
     //clean up memory 
     foreach (System.Drawing.Bitmap image in images) 
     { 
      image.Dispose(); 
     } 
    } 
} 
+2

funcionó muy bien. g.Clear (Color.Transparent) si desea fusionar imágenes PNG para sprites de animación – syclee

+1

finalImage = new System.Drawing.Bitmap (ancho, alto); arroja un error para valores altos de ancho/alto – zeetit

+0

@Anant Dabhi Bien, lamento traer una pregunta anterior, pero la convertí en VB.NET ... ¿Estará superpuesta a otras fotos si las coloco sobre las demás si los píxeles no utilizados/píxeles en blanco en la siguiente imagen es transparente? Si no, ¿hay alguna manera de hacerlo? – Speentie8081