GDI简单的图片处理

前天有个项目需求是在一张图片上面画些东西(点,线,圆等);目标:在Default2.aspx上显示一个可以自由处理的图片

下代码如下:

前台页面代码:

Default2.aspx文件(需要显示处理后的图片页面)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="LoadPic.aspx" alt="#"/>//从Loadpic.aspx加载来的处理后的图片,也就是说,可以把LoadPic.aspx看作一个图片的“路径”
</div>
</form>
</body>
</html>

//文件LoadPic.aspx.cs代码:

using System;

using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class LoadPic: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

Bitmap image1 = (Bitmap)System.Drawing.Image.FromFile("C:\Users\Administrator\Desktop\1242397_104821039_2.jpg", true);//参数1:图片的路径;参数2:Bool值

// Bitmap savepic = new Bitmap(image1,20 ,10);更改图片大小
Graphics g = Graphics.FromImage(image1);//拿到图片的画布,注意在画布上面画东西

//画线
int x1 = 50;
int x2 = 70;
int y1 = 80;
int y2 = 120;
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);//两点确定直线

//画一个圆
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Pen pen = new Pen(Color.Red);//画笔颜色
g.DrawEllipse(pen, 250, 200, 100, 100);//画椭圆的方法,x坐标、y坐标、宽、高,如果是100,则半径为50

//随意写上一些字符串
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));//设置字体
Brush brush = new System.Drawing.SolidBrush(Color.Red);//颜色
g.DrawString("写上一些东西", font, brush, 400, 200);

通过流的操作进行对象的输入输出(输入流,输出流)
System.IO.MemoryStream ms = new System.IO.MemoryStream(); //生成一个数据流
image1.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);保存到流中(输入流)
Response.ClearContent();//清除缓冲区流中的所有内容
Response.ContentType = "image/jbg";
Response.BinaryWrite(ms.ToArray());//将一个二进制字符串写入 HTTP 输出流(输出图片)
g.Dispose();释放Graphics 的资源
image1.Dispose();同样释放

}

}

此时Default2.aspx就会显示相应处理的图片,本例过于简单,如果想处理复杂,可以查MSDN相关GDI操作,希望能起到举一反三的功效。

一览众山小
原文地址:https://www.cnblogs.com/ZLGBloge/p/4159915.html