需求:从数据库中查询出两张图片的相对路径,其中一个为底图,另一个图片需附着在底图上,最终合成为一张图片并保存到项目的Test文件夹中,图片以公司名称分类,每个公司的图片放到一个文件夹中。
数据库信息如下:
代码实现:
try
{
//数据库查询图片信息
using (OracleConnection conn = new OracleConnection(DefaultDBConnection))
{
conn.Open();//打开连接
string SQL = @"select * from (
select t1.BLOCKNAME,substr(BPHOTOPATH,instr(BPHOTOPATH,'/',1,3)+1,instr(BPHOTOPATH,'/',1,4)-instr(BPHOTOPATH,'/',1,3)-1) corp,
t.BPHOTOPATH,t.PPHOTOPATH from as_land_photo t
left join view_dw_landinfo t1 on t.land_id=t1.PID
) order by corp";
OracleCommand cmd = new OracleCommand(SQL, conn);
OracleDataAdapter vDa = new OracleDataAdapter(cmd);
DataSet vDs = new DataSet();
vDa.Fill(vDs);
DataTable dt = vDs.Tables[0];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
string saveFile = PathConvert("Test/" + dt.Rows[i]["CORP"] + "/" + dt.Rows[i]["BLOCKNAME"] + ".jpg");//图片文件名称
string imgBackPath = PathConvert(dt.Rows[i]["BPHOTOPATH"].ToString()); //底图路径
string imgBackExtension = Path.GetExtension(imgBackPath);
string imgPath = PathConvert(dt.Rows[i]["PPHOTOPATH"].ToString()); //图片路径
string imgExtension = Path.GetExtension(imgPath);
if (File.Exists(imgBackPath) == false || File.Exists(imgPath) == false || (imgBackExtension != ".png" && imgBackExtension != ".jpg") || (imgBackExtension != ".png" && imgBackExtension != ".jpg"))
{
logger.Info("文件不存在或不支持该扩展名!");
}
//在调用 Save 方法之前,先判断目录是否存在,若不存在,则创建。
string filePath = PathConvert("Test/" + dt.Rows[i]["CORP"]);//图片文件加名称
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
Image imgBack = Image.FromFile(imgBackPath);
Image img = Image.FromFile(imgPath);
Bitmap bmp = CombinImage(imgBack, img);
bmp.Save(saveFile, ImageFormat.Jpeg);
}
}
}
}
catch (Exception ex)
{
}
#region 合并图片
/// <summary>
/// 合并图片
/// </summary>
/// <param name="imgBack"></param>
/// <param name="img"></param>
/// <param name="xDeviation"></param>
/// <param name="yDeviation"></param>
/// <returns></returns>
public static Bitmap CombinImage(Image imgBack, Image img, int xDeviation = 0, int yDeviation = 0)
{
Bitmap bmp = new Bitmap(imgBack.Width, imgBack.Height);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);
g.DrawImage(img, imgBack.Width / 2 - img.Width / 2 + xDeviation, imgBack.Height / 2 - img.Height / 2 + yDeviation, img.Width, img.Height);
GC.Collect();
return bmp;
}
#endregion
#region 将相对路径转换成绝对路径
/// <summary>
/// 将相对路径转换成绝对路径
/// </summary>
/// <param name="strPath">相对路径</param>
public static string PathConvert(string strPath)
{
//web程序使用
if (HttpContext.Current != null)
{
return HttpContext.Current.Server.MapPath(strPath);
}
else //非web程序引用
{
strPath = strPath.Replace("/", "\\");
if (strPath.StartsWith("\\"))
{
strPath = strPath.TrimStart('\\');
}
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
}
}
#endregion
程序执行结果:
在项目中生成Test文件夹
在Test文件夹中根据公司名称生成了对应的文件夹
每个公司文件夹中生成对应公司的图片