图片处理程序示例,实现功能点有
1、远程图片转换Image对象
2、在图片上添加文字
3、在图片上添加图片
4、将图片进行椭圆形(圆形)切割
5、微软程序处理图片失真。不少人发现图片用微软程序重绘之后,即时什么也不做,图片质量也会压缩,微软的Image.Save方法,不设置压缩质量,是默认保存到图片压缩质量为75,所以保存的图片质量偏低。
代码如下,此处是asp.net中的一般处理程序
public void ProcessRequest(HttpContext context)
{
//产品图片
string ProducePicUrl = "http://img.xxx.com/group1/M00/36/B8/cnHoeV3pxMWANofjAACQFhMkSE0601_s.jpg";
Image img = GetStreamByUrl(ProducePicUrl);
Graphics grap = Graphics.FromImage(img);
//设置输出图片质量
grap.CompositingQuality = CompositingQuality.HighQuality;
grap.SmoothingMode = SmoothingMode.HighQuality;
grap.InterpolationMode = InterpolationMode.HighQualityBicubic;
//在图片上添加文字
grap.DrawString("中国山东找蓝翔", new Font("宋体", 20, FontStyle.Bold), Brushes.Blue, new PointF(29, 29));
//企业logo图片
string ComPicUrl = "http://img.xxx.com/group1/M00/2D/62/cnHoeVsfISeAEPqhAAA5bjwdSWo698_s.jpg";
Image Comimg = GetStreamByUrl(ComPicUrl);
//图片圆形切割
Comimg = CutEllipse(Comimg, new Rectangle(0, 0, Comimg.Width, Comimg.Height), new Size(100, 100));
//图片上添加图片
grap.DrawImage(Comimg, new Rectangle(img.Width - 100, 0, 100, 100),
0, 0, Comimg.Width, Comimg.Height, GraphicsUnit.Pixel);
EncoderParameters ps = new EncoderParameters(1);
EncoderParameter p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
ps.Param[0] = p;
ImageCodecInfo imgcodec = GetCodecInfo("image/jpeg");
img.Save(context.Response.OutputStream, imgcodec, ps);
//img.Save(context.Response.OutputStream, ImageFormat.Jpeg);常用图片保存,质量被压缩
context.Response.ContentType = "image/jpeg";
}
/// <summary>
/// 图片剪切成椭圆形
/// </summary>
/// <param name="img">原始Image对象</param>
/// <param name="rec">被切割图片的矩形范围</param>
/// <param name="size">椭圆的尺寸</param>
/// <returns></returns>
private Image CutEllipse(Image img, Rectangle rec, Size size)
{
Bitmap bitmap = new Bitmap(size.Width, size.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
using (TextureBrush br = new TextureBrush(img, System.Drawing.Drawing2D.WrapMode.Clamp, rec))
{
br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.FillEllipse(br, new Rectangle(Point.Empty, size));
}
}
return bitmap;
}
private ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType) return ici;
}
return null;
}
/// <summary>
/// 获取远程图片的Image对象
/// </summary>
/// <returns></returns>
public Image GetStreamByUrl(string imgurl)
{
WebRequest myrequest = WebRequest.Create(imgurl);
myrequest.Timeout = 3 * 1000;
WebResponse myresponse = myrequest.GetResponse();
Stream imgstream = myresponse.GetResponseStream();
Image img = Image.FromStream(imgstream);
myrequest.Abort();
myresponse.Close();
return img;
}
最终效果:右侧圆形区域是企业Logo
参考资料:https://blog.csdn.net/chinacsharper/article/details/50854852