联系我们

为客户提供超预期的高品质网站设计!

图片base64格式,另存为图片

2018-6-20 0:00:00

图片的base64位信息由ajax json提交到 ashx后台:

方法一:

orderID = context.Request.Form["orderID"].ToString();
pic = context.Request.Form["pic"].ToString(); //pic是base64编码的数据

string filepath = "/upload/" + DateTime.Now.ToString("yyyyMMdd") + "/";
if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(filepath)) == false)//如果不存在就创建file文件夹
{
    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(filepath));
}

string picName = DateTime.Now.ToString("yyyyMMddHHmmss");
string tFullName = System.Web.HttpContext.Current.Server.MapPath(filepath) + picName + ".jpg";

byte[] bytes = Convert.FromBase64String(pic); //转字节流
File.WriteAllBytes(tFullName, bytes);

context.Response.Write("ok");

//以上是直接保存方式,没有对图像进行大小的处理。


方法二:

...

...

byte[] bytes = Convert.FromBase64String(pic);

Stream oStream = new MemoryStream(bytes);


System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
int oWidth = oImage.Width; //原图宽度   
int oHeight = oImage.Height; //原图高度   
int tWidth = 800; //设置缩略图初始宽度   
int tHeight = 800; //设置缩略图初始高度  
        //按比例计算出缩略图的宽度和高度   
        if (oWidth >= oHeight)
        {
            tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
        }
        else
        {
            tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
        }


Bitmap tImage = new Bitmap(tWidth, tHeight);
Graphics g = Graphics.FromImage(tImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法   
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度   
g.Clear(Color.Transparent); //清空画布并以透明背景色填充   
g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);


//string oFullName = Server.MapPath(".") + "/image/" + "o" + DateTime.Now.ToShortDateString().Replace("-", "") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".jpg"; //保存原图的物理路径   
//string  tFullName = Server.MapPath(".") + "/image/"+ "/image/" + "t" + DateTime.Now.ToShortDateString().Replace("-", "") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".jpg"; //保存缩略图的物理路径 



try
{
    //以JPG格式保存图片   
    // oImage.Save(oFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
    tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);

   
    context.Response.Write("ok");
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    //释放资源   
    oImage.Dispose();
    g.Dispose();
    tImage.Dispose();
}


上一条新闻:asp.net 实体类 存入 数据库
下一条新闻:mysql创建二表视图

 

4008-520-214 54057491 info@maolian.net