标签:
public byte[] TransPIc(string picpath) //将图片统一大小并转为byte
{
Image imgPhoto = Image.FromFile(picpath);
int oldx = imgPhoto.Width;
int oldy = imgPhoto.Height;
//新图片尺寸
int cx = 255;
int cy = 255;
if (oldx >= oldy)
cy =Convert.ToInt32(255 * Convert.ToDouble(oldy) / Convert.ToDouble(oldx));
if (oldx < oldy)
cx = Convert.ToInt32(255 * Convert.ToDouble(oldx) / Convert.ToDouble(oldy));
int dx = 255 - cx;
int dy = 255 - cy;
Image newImage = new Bitmap(255, 255);
Graphics g = Graphics.FromImage(newImage);
//清除画布,背景设置为白色
g.Clear(System.Drawing.Color.White);
// 设置画布的描绘质量
Image bm = new Bitmap(255,255); //先设置一空白图像
if (dx > 0) //竖排图像
{
//在原图像两侧各插入dx/2宽,255高的空白图像
//图像合并
bm = new Bitmap(dx/2, 255);
g.DrawImage(bm, 0, 0, dx/2, 255); //画布左侧添加空白
g.DrawImage(imgPhoto, dx/2, 0, cx, cy); //从dx/2处添加原竖排图像,此时x方向右端仍有dx/2的空白
g.DrawImage(bm, 255-dx/2, 0, dx/2, 0); //补上右侧的空白图像
}
if (dy > 0)
{
bm = new Bitmap(255, dy);
g.DrawImage(bm, 0, 0, dx, dy);
g.DrawImage(imgPhoto, dx, dy, cx, cy);
}
g.Dispose();
imgPhoto.Dispose();
MemoryStream ms = new MemoryStream();
newImage.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imagedata = ms.GetBuffer();
newImage.Dispose();
ms.Dispose();
bm.Dispose();
return imagedata;
}
或者
//新图片尺寸
int cx = treatx;
int cy = treaty;
double r16_9 = 16.0 / 9.0;
Image imgPhoto = Image.FromFile(picpath);
int oldx = imgPhoto.Width;
int oldy = imgPhoto.Height;
int dltx = 0;
int dlty = 0;
if (oldx >= oldy) //正常横拍照片
{
double oldxyrate = Convert.ToDouble(oldx) / Convert.ToDouble(oldy);
if (oldxyrate > r16_9) //原图偏宽
{
int justx = Convert.ToInt32(oldy * r16_9);
dltx = (oldx - justx) / 2; //原图两侧各应该剪裁多少
}
else if (r16_9 > oldxyrate) //原图偏高
{
int justy = Convert.ToInt32(oldx / r16_9);
dlty = (oldy - justy) / 2; //原图上下各应该剪裁多少
}
}
if (oldy > oldx) //竖拍照片 也按9:16的标准
{
cx = treatxx;
cy = treaty;
double r9_16 = 9.0 / 16.0;
double oldxyrate = Convert.ToDouble(oldx) / Convert.ToDouble(oldy);
if (oldxyrate > r9_16) //原图偏宽
{
int justx = Convert.ToInt32(oldy * r9_16);
dltx = (oldx - justx) / 2; //原图两侧各应该剪裁多少
}
else if (r9_16 > oldxyrate) //原图偏高
{
int justy = Convert.ToInt32(oldx / r9_16);
dlty = (oldy - justy) / 2; //原图上下各应该剪裁多少
}
}
Image newImage = new Bitmap(cx, cy);
Graphics g = Graphics.FromImage(newImage);
g.DrawImage(imgPhoto, new Rectangle(0, 0, cx, cy), new Rectangle(dltx, dlty, imgPhoto.Width - 2 * dltx, imgPhoto.Height - 2 * dlty), GraphicsUnit.Pixel);
g.Dispose();
newImage.Dispose();
imgPhoto.Dispose();
return newImage;
标签:
原文地址:http://www.cnblogs.com/mol1995/p/5965044.html