合并两个图片成一个图片的代码

合并两个图片成一个图片的代码
代码实现:
enum ImageMergeOrientation
{
Horizontal,
Vertical
}
private void CombineImages(FileInfo[] files, string toPath, ImageMergeOrientation mergeType = ImageMergeOrientation.Vertical)
{
//change the location to store the final image.
// URL:http://www.bianceng.cn/Programming/csharp/201410/45751.htm
var finalImage = toPath;
var imgs = files.Select(f => Image.FromFile(f.FullName));

        var finalWidth = mergeType == ImageMergeOrientation.Horizontal ?  
            imgs.Sum(img => img.Width) :  
            imgs.Max(img => img.Width);  

        var finalHeight = mergeType == ImageMergeOrientation.Vertical ?  
            imgs.Sum(img => img.Height) :  
            imgs.Max(img => img.Height);  

        var finalImg = new Bitmap(finalWidth, finalHeight);  
        Graphics g = Graphics.FromImage(finalImg);  
        g.Clear(SystemColors.AppWorkspace);  

        var width = finalWidth;  
        var height = finalHeight;  
        var nIndex = 0;  
        foreach (FileInfo file in files)  
        {  
            Image img = Image.FromFile(file.FullName);  
            if (nIndex == 0)  
            {  
                g.DrawImage(img, new Point(0, 0));  
                nIndex++;  
                width = img.Width;  
                height = img.Height;  
            }  
            else
            {  
                switch (mergeType)  
                {  
                    case ImageMergeOrientation.Horizontal:  
                        g.DrawImage(img, new Point(width, 0));  
                        width += img.Width;  
                        break;  
                    case ImageMergeOrientation.Vertical:  
                        g.DrawImage(img, new Point(0, height));  
                        height += img.Height;  
                        break;  
                    default:  
                        throw new ArgumentOutOfRangeException("mergeType");  
                }  
            }  
            img.Dispose();  
        }  
        g.Dispose();  
        finalImg.Save(finalImage, System.Drawing.Imaging.ImageFormat.Tiff);  
        finalImg.Dispose();  
    }

代码说明:
根据参数进行横向或纵向合并图片
如果为横向,图片高度为最高的那张;如果纵向则宽度为最宽的那张
UT 代码:
[TestMethod]
public void Combine_Multiple_SampleImages_IntoOne()
{
const string folderPath = “C:\Users\Public\Pictures\Sample Pictures”;
var images = new DirectoryInfo(folderPath).GetFiles(“*.jpg”, SearchOption.TopDirectoryOnly);

        CombineImages(images, "C:/FinalImage_H.tiff");  
        CombineImages(images, "C:/FinalImage_V.tiff", ImageMergeOrientation.Vertical);  
    }

VB代码
Imports System.Drawing

Module Module1

Sub Main()

    Dim img As New List(Of Image)

    img.Add(Image.FromFile("D:\Old\_old\D\5265847638_525279bf46[1].jpg"))
    img.Add(Image.FromFile("D:\Old\_old\D\5265847638_525279bf46[1].jpg"))
    img.Add(Image.FromFile("D:\Old\_old\D\5265847638_525279bf46[1].jpg"))

    Dim w = img(0).Width
    Dim h = img(0).Height

    Dim i As New Bitmap(w, h * img.Count)

    Dim g As Graphics = Graphics.FromImage(i)

    For k = 0 To img.Count - 1

        g.DrawImage(img(k), 0, k * h, w, h)

    Next

    i.Save("D:\Old\_old\D\a.jpg", Imaging.ImageFormat.Jpeg)

    g.Dispose()

End Sub

End Module

Java代码

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class DrawImage {
public static boolean Merge(BufferedImage image1, BufferedImage image2,
int posw, int posh,String path) {

//合并两个图像
int w1 = image1.getWidth();
int h1 = image1.getHeight();
int w2 = image2.getWidth();
int h2 = image2.getHeight();

BufferedImage imageSaved = new BufferedImage(w1, h1,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = imageSaved.createGraphics();
g2d.drawImage(image1, null, 0, 0);
for (int i = 0; i < w2; i++) {
for (int j = 0; j < h2; j++) {
int _rgb1 = image1.getRGB(i + posw, j + posh);
int _rgb2 = image2.getRGB(i, j);
if (_rgb1 != _rgb2) {
_rgb2 = _rgb1 & _rgb2;
}
imageSaved.setRGB(i + posw, j + posh, _rgb2);
}
}

boolean b = false;
try {
File file = new File(path);
b = ImageIO.write(imageSaved, “jpg”, file);
} catch (IOException ie) {
ie.printStackTrace();
}
return b;
}

public static void main(String[] args) throws Exception {
String p = “f:/pp/img_1.jpeg”;
DrawImage di = new DrawImage();
InputStream imagein1 = new FileInputStream(p);
BufferedImage image1 = ImageIO.read(imagein1);
int posw = 50,posh = 100;
InputStream imagein2 = new FileInputStream(“f:/pp/1.jpg”);
BufferedImage image2 = ImageIO.read(imagein2);
di.Merge(image1, image2, posw, posh,p);
//System.out.println(“ok”);
}
}

C# code 合并图片的功能
string path = Server.MapPath(“~/temp/”);
string imgFilePath1 = path + “123456ASDFG.JPG”;
string imgFilePath2 = path + “aaaaaaaaaaa.JPG”;
if (!File.Exists(imgFilePath1))
File.Create(imgFilePath1);
System.Drawing.Image img1 = System.Drawing.Image.FromFile(imgFilePath1);
System.Drawing.Image img2 = System.Drawing.Image.FromFile(imgFilePath2);
Bitmap newImg = new Bitmap((img1.Width > img2.Width) ? img1.Width : img2.Width, img1.Height + img2.Height);
Graphics g = Graphics.FromImage(newImg);
g.Clear(Color.Blue);
g.DrawImageUnscaled(img1, 0, 0);
g.DrawImageUnscaled(img2,0, img1.Height);

    img1.Dispose();

    newImg.Save(imgFilePath1);
    g.Dispose();

直接调用控制台命令

1
2
3
4
Process p = new Process();
p.StartInfo.FileName =”cmd.exe”;
p.StartInfo.Arguments = string.Format(“copy /b \”{0}\”+ \”{1}\” \”{2}\”“,file1,file2,dest);//file1,file2是图片路径,dest是保存路径
p.Start();

///
/// 图片裁剪,生成新图,保存在同一目录下,名字加_new,格式1.png 新图1_new.png
///
/// 要修改图片完整路径
/// 修改起点x坐标
/// 修改起点y坐标
/// 新图宽度
/// 新图高度
public static void caijianpic(String picPath,int x,int y,int width,int height)
{
//图片路径
String oldPath = picPath;
//新图片路径
String newPath = System.IO.Path.GetExtension(oldPath);
//计算新的文件名,在旧文件名后加_new
newPath = oldPath.Substring(0, oldPath.Length - newPath.Length) + “_new” + newPath;
//定义截取矩形
System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(x, y, width, height);
//要截取的区域大小
//加载图片
System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(System.IO.File.ReadAllBytes(oldPath)));
//判断超出的位置否
if ((img.Width < x + width) || img.Height < y + height)
{
MessageBox.Show(“裁剪尺寸超出原有尺寸!”);
img.Dispose();
return;
}
//定义Bitmap对象
System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img);
//进行裁剪
System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
//保存成新文件
bmpCrop.Save(newPath);
//释放对象
img.Dispose(); bmpCrop.Dispose();
}

   /// <summary>  
   /// 调用此函数后使此两种图片合并,类似相册,有个  
   /// 背景图,中间贴自己的目标图片  
   /// </summary>  
   /// <param name="sourceImg">粘贴的源图片</param>  
   /// <param name="destImg">粘贴的目标图片</param>  
   public static Image CombinImage(string sourceImg, string destImg)  
   {  
       Image imgBack = System.Drawing.Image.FromFile(sourceImg); //相框图片   
       Image img = System.Drawing.Image.FromFile(destImg); //照片图片  
       //从指定的System.Drawing.Image创建新的System.Drawing.Graphics         
       Graphics g = Graphics.FromImage(imgBack);  
       //g.DrawImage(imgBack, 0, 0, 148, 124); // g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);  
       g.FillRectangle(System.Drawing.Brushes.Black, -50, -50, (int)212, ((int)203));//相片四周刷一层黑色边框,这里没有,需要调尺寸  
       //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);  
       g.DrawImage(img, -50, -50, 212, 203);  
       GC.Collect();  
       string saveImagePath ="D:/测试文件夹/sss.png";  
       //save new image to file system.  
       imgBack.Save(saveImagePath, ImageFormat.Png);  
       return imgBack;  
   }  
// AddTextDlg.cpp : implementation file // #include "stdafx.h" #include "Test.h" #include "AddTextDlg.h" #include ".\addtextdlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAddTextDlg dialog CAddTextDlg::CAddTextDlg(CWnd* pParent /*=NULL*/) : CDialog(CAddTextDlg::IDD, pParent) { //{{AFX_DATA_INIT(CAddTextDlg) m_strText = _T(""); //}}AFX_DATA_INIT m_strBmpFilePath = ""; ZeroMemory(&m_bmpIfHi, sizeof(BITMAPINFOHEADER)); m_dwSize = 0; m_lpDIBits = NULL; } void CAddTextDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAddTextDlg) DDX_Control(pDX, IDC_EDIT_TEXT, m_edtText); DDX_Control(pDX, IDC_STATIC_SHOW, m_BmpShow); DDX_Text(pDX, IDC_EDIT_TEXT, m_strText); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAddTextDlg, CDialog) //{{AFX_MSG_MAP(CAddTextDlg) ON_EN_CHANGE(IDC_EDIT_TEXT, OnChangeEditText) //}}AFX_MSG_MAP ON_BN_CLICKED(IDOK, OnBnClickedOk) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CAddTextDlg message handlers BOOL CAddTextDlg::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here m_edtText.EnableWindow(FALSE); int nCharLimit = 0; if (m_strBmpFilePath.GetLength() > 0) {//传文件路径 if (m_BmpShow.SetReadBmpPath(m_strBmpFilePath, &nCharLimit)) { m_edtText.EnableWindow(); m_edtText.SetLimitText(nCharLimit); } else { PostMessage(WM_CLOSE, 0, 0); } } else {//传位图信息和数据 if (NULL == m_lpDIBits) { PostMessage(WM_CLOSE, 0, 0); } if (m_BmpShow.SetBmpInfo(&m_bmpIfHi, m_lpDIBits, &nCharLimit)) { m_edtText.EnableWindow(); m_edtText.SetLimitText(nCharLimit); } else { PostMessage(WM_CLOSE, 0, 0); } } return TRUE; // return TRUE unless you set the focus to a control } void CAddTextDlg::OnChangeEditText() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. UpdateData(); m_BmpShow.SetBmpText(m_strText); // TODO: Add your control notification handler code here } BOOL CAddTextDlg::SetBmpFilePath(LPCTSTR pszPath) { if (0 == _mbstrlen(pszPath)) { return FALSE; } m_strBmpFilePath = pszPath; return TRUE; } void CAddTextDlg::OnOK() { // TODO: Add extra validation here if (m_strBmpFilePath.GetLength() > 0) { m_BmpShow.SetSaveBmpPath(m_strBmpFilePath); } if (m_lpDIBits != NULL) { delete[] m_lpDIBits; m_lpDIBits = NULL; } m_lpDIBits = new BYTE[m_dwSize]; m_BmpShow.SaveModify(&m_bmpIfHi, m_lpDIBits); CDialog::OnOK(); } void CAddTextDlg::OnCancel() { // TODO: Add extra cleanup here CDialog::OnCancel(); } BOOL CAddTextDlg::SetBmpInfo(const LPBITMAPINFOHEADER lpbmih, const LPVOID lpvBits) { ASSERT((lpbmih != NULL) && (lpvBits != NULL)); m_strBmpFilePath = ""; if (m_lpDIBits != NULL) { delete[] m_lpDIBits; m_lpDIBits = NULL; } if ((lpbmih->biBitCount < 16) || (lpbmih->biBitCount > 32)) { return FALSE; } memcpy(&m_bmpIfHi, lpbmih, sizeof(BITMAPINFOHEADER)); m_BmpShow.ComputeImageSize(&m_bmpIfHi, &m_dwSize); /* if (m_dwSize != lpbmih->biSizeImage) { return FALSE; }*/ m_lpDIBits = new BYTE[m_dwSize]; memcpy(m_lpDIBits, lpvBits, lpbmih->biSizeImage); // memcpy(m_lpDIBits, lpvBits, m_dwSize); return TRUE; } CAddTextDlg::~CAddTextDlg() { if (m_lpDIBits != NULL) { delete[] m_lpDIBits; m_lpDIBits = NULL; } } BOOL CAddTextDlg::GetBmpInfo(LPBITMAPINFOHEADER lpbmih, LPVOID lpvBits, LPDWORD pdwSize) { memcpy(lpbmih, &m_bmpIfHi, sizeof(BITMAPINFOHEADER)); *pdwSize = m_dwSize; memcpy(lpvBits, m_lpDIBits, m_dwSize); return TRUE; } void CAddTextDlg::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 OnOK(); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值