asp.net 图片截图

前台代码

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="cutPic.aspx.cs" Inherits="test_cutPic" %>
<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.01 transitional//en" "http://www.w3c.org/tr/1999/rec-html401-19991224/loose.dtd">
<html>
	<head>
<title>图片的无级截取</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="js/cutpic.js" type="text/javascript"></script>
<style type="text/css">
#rRightDown,#rLeftDown,#rLeftUp,#rRightUp,#rRight,#rLeft,#rUp,#rDown{position:absolute;background:#F00;width:5px; height:5px; z-index:500; font-size:0;}
#dragDiv{border:1px solid #000000;}
</style>


<%--<script type="text/javascript">
    //1001代表文件名  是userinfo的id  每种用户对用不同文件夹,这个可以避免重复出现,
    //或获取不到指定文件夹
    window.onload = function ShowImg(imagePath) {
    var s = imagePath;
    var imagePath1 = (typeof (imagePath) != "undefined") ? imagePath : "http://192.168.1.100/xxx/xxxx/1001/316X450.jpg"; var ic = new ImgCropper("bgDiv", "dragDiv", imagePath1, 200, 200, { Right: "rRight", Left: "rLeft", Up: "rUp", Down: "rDown", RightDown: "rRightDown", LeftDown: "rLeftDown", RightUp: "rRightUp", LeftUp: "rLeftUp"
        });
    }
</script>--%>

</head>
<%--<body onload="ShowImg('');">--%>

<body>
    <form id="form1" runat="server">
   <div id="bgDiv" style="width:400px; height:500px;">
        <div id="dragDiv">
          <div id="rRightDown" style="right:0; bottom:0;"> </div>
          <div id="rLeftDown" style="left:0; bottom:0;"> </div>
          <div id="rRightUp" style="right:0; top:0;"> </div>
          <div id="rLeftUp" style="left:0; top:0;"> </div>
          <div id="rRight" style="right:0; top:50%;"> </div>
          <div id="rLeft" style="left:0; top:50%;"> </div>
          <div id="rUp" style="top:0; left:50%;"> </div>
          <div id="rDown" style="bottom:0;left:50%;"></div>
        </div>
      </div>


    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button2" runat="server" Text="上传" onclick="Button2_Click" />
    <asp:Button ID="Button1" runat="server" Text="截取" onclick="Button1_Click" />
    <div>
<input id="T" value="0" runat="server" />
<input id="L" value="0" runat="server" />
<input id="W"  runat="server" />
<input id="H"  runat="server" />
    </div>
    <img id="b" runat="server" visible="false" />
    
    </form>
</body>
</html>

 


后台代码

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

using System.Text;

public partial class test_cutPic : System.Web.UI.Page
{
    private  int imgwidth = 600;
    private  int imgheight = 450;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (ViewState["path"] != null)
                showImages(ViewState["path"].ToString(), int.Parse(ViewState["imgwidth"].ToString()), int.Parse(ViewState["imgheight"].ToString()));
            else
                showImages("", imgwidth, imgheight);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {//截取
        int t = int.Parse(this.T.Value);int l = int.Parse(this.L.Value);int w = int.Parse(this.W.Value);int h = int.Parse(this.H.Value);
        string strPath = (ViewState["path"] != null) ? ViewState["path"].ToString() : "resizeimages/main.jpg";

        Image image = Image.FromFile(Server.MapPath(strPath)); 

        Bitmap bitmap = new Bitmap(w,h); 
        Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
        Graphics canvas = Graphics.FromImage(bitmap);
        int randnum = rand.Next(0, int.MaxValue);
        Rectangle rec = new Rectangle(l, t, w, h);
        GraphicsUnit units = GraphicsUnit.Pixel; 
        canvas.DrawImage(image, 0, 0, rec, units);

        string imgName = (ViewState["imgName"] != null) ? ViewState["imgName"].ToString() : "main.jpg";
        bitmap.Save(Server.MapPath(strPath).Replace(imgName, randnum.ToString() + ".jpg"));
        //bitmap.Save(Server.MapPath("resizeimages/main.jpg").Replace("main.jpg", randnum.ToString() + ".jpg"));
        canvas.Dispose(); 
        image.Dispose(); 
        bitmap.Dispose(); 
        this.b.Visible = true; 
        this.b.Src = "resizeimages/" + randnum + ".jpg";
        if (ViewState["path"] != null)
            showImages(ViewState["path"].ToString(), int.Parse(ViewState["imgwidth"].ToString()), int.Parse(ViewState["imgheight"].ToString()));
        else
            showImages("", imgwidth, imgheight);
        
        

    }
    protected void Button2_Click(object sender, EventArgs e)
    {//上传
        //获取上传图片的宽、高 便于后期配合需求组织判断
        //Stream stream = this.FileUpload1.PostedFile.InputStream;
        //Image image = System.Drawing.Image.FromStream(stream);
        //int a = image.Width;
        //int b = image.Height;

        string filename = FileUpload1.FileName;
        //获得图片名
        //ViewState["imgName"] = filename;


        string extension = System.IO.Path.GetExtension(filename).ToLower();
        if (extension == ".jpeg" || extension == ".jpg" || extension == ".png" || extension == ".gif")
        {
            DateTime dt = DateTime.Now;
            string truefilename = string.Format("{0:yyyyMMddHHmmssffff}", dt) + extension;
            ViewState["imgName"] = truefilename;

            //获得图片路径
            string path = "resizeimages/";
            path += truefilename;
            ViewState["path"] = path;

            FileUpload1.SaveAs(Server.MapPath(path));

            Image img = Image.FromFile(Server.MapPath(path));
            ViewState["imgwidth"] = img.Width;
            ViewState["imgheight"] = img.Height;

        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "myscript", "<script>alert('请上传这几种格式.jpg|.png|.jpeg|.gif的图片格式!');</script>");
        }
        if (ViewState["path"] != null)
            showImages(ViewState["path"].ToString(), int.Parse(ViewState["imgwidth"].ToString()), int.Parse(ViewState["imgheight"].ToString()));
        else
            showImages("", imgwidth, imgheight);
    }

    public void showImages(string imagePath, int imgwidth, int imgheight)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<script type=\"text/javascript\">");
        sb.Append("window.onload = function ShowImg(){");
        //sb.Append("window.onload = function ShowImg(imagePath){");
        //sb.Append("var imagePath1 = (typeof(imagePath) != \"undefined\") ? imagePath : \"resizeimages/main.jpg\";");
        if (!string.IsNullOrEmpty(imagePath))
            sb.Append("var imagePath1=\""+imagePath+"\";");
        else
            sb.Append("var imagePath1=" + "\"resizeimages/main.jpg\";");

        sb.Append("var ic = new ImgCropper(\"bgDiv\", \"dragDiv\", imagePath1, " + imgwidth + ", " + imgheight + ", {");
        sb.Append("Right: \"rRight\", Left: \"rLeft\", Up: \"rUp\", Down: \"rDown\",");
        sb.Append("RightDown: \"rRightDown\", LeftDown: \"rLeftDown\", RightUp: \"rRightUp\", LeftUp: \"rLeftUp\"");
        sb.Append("});");
        sb.Append("}");
        sb.Append("</script>");
        ClientScript.RegisterStartupScript(this.GetType(), "LoadPicScript", sb.ToString());

    }
}


效果看图:

图2

 

总结: 图片截取注意事项

1, 截取图片保存另一台服务器配置地址

如: <appSettings>
  <add key="ImageShowUrl" value="http://192.168.1.100/ty/"/>  //这个是图片显示地址

<add key="TouristImageUpload" value="\\192.168.1.100\ty\ImageUploadFile\"/>//这个是图片保存地址

</appSettings>

2, 防止替换图片名字一样,图片没有显示,在地址后面加个随机数即可解决

Random rand = new Random();

tp.ImageUrl = pUrl + "ImageUploadFile/" + dt.Rows[0]["ID"].ToString() + "/" + filename + "?"+rand.Next();

图片显示地址

http://192.168.1.100/ty/ImageUploadFile/12262/160X120.jpg?1530327673

 

3,图片一直名字不同,如 时分秒组织的图片名字 不要考虑第2种问题。

 

演示代码下载地址:

http://download.csdn.net/download/suntanyong88/3723839

你可能感兴趣的:(server,String,asp.net,Path,button,extension)