c# web 图片上传帮助类, 多图上传,保存原图,800*800,400*400缩略图

网友投稿 308 2022-09-25

c# web 图片上传帮助类, 多图上传,保存原图,800*800,400*400缩略图

c# web 多图上传,保存原图,800*800,400*400缩略图

帮助类内容:

1.基本上传图片

2.上传图片(原图上传,自定义路径和名称)

3.上传图片(图片byte[],自定义路径和名称)

4.上传等比缩放图片

5.给图片加上水印

6.产生图片验证码

7.根据地址获取图片宽和高

8.根据地址获取图片高度

9.图片无损压缩上传

业务源码

引用命名空间

using QuanXi.Web.UI;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Web;

业务逻辑代码

private void UploadImgs(HttpContext context) { HttpFileCollection files = context.Request.Files; StringBuilder sb = new StringBuilder(); var path = "/uploads/base/photo/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM")+ DateTime.Now.ToString("dd") + "/"; string imgsurl = "",imgurls="",imgurlb=""; if (files.Count <= 0) { sb.Append("{\"status\": \"-1\",\"msg\":\"未收到上传图片\"}"); } else { for (int i = 0; i < files.Count; i++) { var strPath = path + files[i].FileName; //files[i].SaveAs(strPath); HttpPostedFile imgfile = files[i]; //文件真实类型 string strFileType = imgfile.ContentType; string strFileName = imgfile.FileName; //文件扩展名 string strFileExtendName = strFileName.Substring(strFileName.LastIndexOf(".") + 1).ToLower(); if (strFileType.StartsWith("image") && (strFileExtendName == "bmp" || strFileExtendName == "jpg" || strFileExtendName == "jpeg" || strFileExtendName == "png" || strFileExtendName == "gif")) { //文件大小 long intFileSize = imgfile.ContentLength; //取当前时间的字符串 string strNowTimeString = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString(); //文件的新名称 string strNewFileName = strNowTimeString + intFileSize.ToString() + "." + strFileExtendName; //保存原图 AttachmentInfo imgresult = ImageHelper.UploadImage(imgfile, path, strNewFileName); imgsurl += imgresult.FileUrl + "|"; Stream stmUpload = imgfile.InputStream; //保存压缩后的小图 Stream sstmUpload = stmUpload; ImageInfo othumb1 = new ImageInfo(); othumb1.Width = 400; othumb1.Height = 400; othumb1.Tag = "s"; string sSaveFile = HttpContext.Current.Server.MapPath(path) + othumb1.Tag + "_" + strNewFileName; if (ImageHelper.ResizeImage(sstmUpload, sSaveFile, othumb1.Width, othumb1.Height)) { imgurls += path + othumb1.Tag + "_" + strNewFileName + "|"; } //sstmUpload.Close(); //sstmUpload.Dispose(); //保存压缩后的大图 Stream bstmUpload = stmUpload; ImageInfo othumb2 = new ImageInfo(); othumb2.Width = 800; othumb2.Height = 800; othumb2.Tag = "b"; string bSaveFile = HttpContext.Current.Server.MapPath(path) + othumb2.Tag + "_" + strNewFileName; if(ImageHelper.ResizeImage(bstmUpload, bSaveFile, othumb2.Width, othumb2.Height)) { imgurlb += path + othumb2.Tag + "_" + strNewFileName + "|"; } stmUpload.Close(); stmUpload.Dispose(); } } if (imgsurl.LastIndexOf("|")==imgsurl.Length-1) { imgsurl = imgsurl.Substring(0, imgsurl.Length - 1); } if (imgurls.LastIndexOf("|") == imgurls.Length-1) { imgurls = imgurls.Substring(0,imgurls.Length-1); } if (imgurlb.LastIndexOf("|")== imgurlb.Length-1) { imgurlb = imgurlb.Substring(0,imgurlb.Length-1); } sb.Append("{\"status\": \"0\",\"msg\":\"上传成功\",\"imgsurl\":\""+ imgsurl + "\",\"imgurls\":\"" + imgurls + "\",\"imgurlb\":\"" + imgurlb + "\"}"); } string strCallBack = RequestProcess.RequestString("callback"); if (strCallBack != "") { HttpContext.Current.Response.Write(strCallBack + "(" + sb.ToString() + ");"); HttpContext.Current.Response.End(); } else { HttpContext.Current.Response.Write(sb.ToString()); HttpContext.Current.Response.End(); } }

返回结果

{ "status":"0", "msg":"上传成功", "imgsurl":"/uploads/base/photo/2022/0323//2022323953078996789.jpg", "imgurls":"/uploads/base/photo/2022/0323/s_2022323953078996789.jpg", "imgurlb":"/uploads/base/photo/2022/0323/b_2022323953078996789.jpg"}

imgsurl:原图

imgurls:压缩后的小图 400*400

imgurlb:压缩后的大图 800*800

图片上传帮助类 ImageHelper.cs

引用命名空间

using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Drawing;using System.Web;using System.Drawing.Imaging;using System.Drawing.Drawing2D;

帮助类 ImageHelper.cs

public class ImageInfo { private int m_intWidth = 0; private int m_intHeight = 0; private string m_strTag = ""; public int Width { set { m_intWidth = value; } get { return m_intWidth; } } public int Height { set { m_intHeight = value; } get { return m_intHeight; } } public string Tag { set { m_strTag = value; } get { return m_strTag; } } } public class ImageHelper { #region 上传图片 ///

/// /// /// 上传过的文件 /// 分类过的路径 /// 是否保持原来的路径 /// /// 图片信息 /// static public AttachmentInfo UploadImage(HttpPostedFile postedFile, string upLoadForder, bool isSaveOriginal, bool isWaterImage, List thumbnails) { string strRootFolder = ""; AttachmentInfo oaiInfo = new AttachmentInfo(); //文件名 string strFileName = postedFile.FileName; //文件扩展名 string strFileExtendName = strFileName.Substring(strFileName.LastIndexOf(".") + 1).ToLower(); //文件真实类型 string strFileType = postedFile.ContentType; //文件大小 int intFileSize = postedFile.ContentLength; //文件上传的文件夹目录(绝对路径) string strFolderMapPath; if (!upLoadForder.Equals("")) { strFolderMapPath = HttpContext.Current.Server.MapPath(upLoadForder); } else { strFolderMapPath = HttpContext.Current.Server.MapPath("/uploads/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/"); } //建立上传目录 if (!Directory.Exists(strFolderMapPath)) { Directory.CreateDirectory(strFolderMapPath); } //取当前时间的字符串 string strNowTimeString = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString(); //文件的新名称(当前日期+文件大小+文件扩展名) string strNewFileName = strNowTimeString + intFileSize.ToString() + "." + strFileExtendName; //最终保存文件的路径(文件绝对路径+新生成的文件的新名称) string strFileMapPath = strFolderMapPath + "/" + strNewFileName; //返回的文件虚拟目录(相对路径) string strFileUploadPath = upLoadForder + "/" + strNewFileName; #region 如果为图片类型 if (strFileType.StartsWith("image") && (strFileExtendName == "bmp" || strFileExtendName == "jpg" || strFileExtendName == "jpeg" || strFileExtendName == "png" || strFileExtendName == "gif")) { //是否保存原图 if (isSaveOriginal) { //保存原图 postedFile.SaveAs(strFileMapPath); } if (thumbnails != null && thumbnails.Count > 0) { string strSaveFile = ""; foreach (ImageInfo thumb in thumbnails) { if (thumb.Tag != "") { strSaveFile = strFolderMapPath + "/" + thumb.Tag + "_" + strNewFileName; } else { strSaveFile = strFolderMapPath + "/" + strNewFileName; } ResizeImage(postedFile.InputStream, strSaveFile, thumb.Width, thumb.Height); } } } #endregion else { //保存文件 postedFile.SaveAs(strFileMapPath); } //HttpContext.Current.Response.Write(strFileUploadPath); //附件属性 oaiInfo.FileName = strNewFileName; oaiInfo.FilePath = upLoadForder; oaiInfo.FileUrl = upLoadForder + strNewFileName; oaiInfo.FileSize = intFileSize; return oaiInfo; } #endregion #region 上传图片(原图上传,自定义路径和名称) /// /// 上传图片(原图上传,自定义路径和名称) /// /// 上传控件 /// 存放相对路径 /// 新文件名 /// static public AttachmentInfo UploadImage(HttpPostedFile postedFile, string filePath, string fileName) { AttachmentInfo oaiInfo = new AttachmentInfo(); 文件名 string strFileName = postedFile.FileName; //文件扩展名 string strFileExtendName = strFileName.Substring(strFileName.LastIndexOf(".") + 1).ToLower(); //文件真实类型 string strFileType = postedFile.ContentType; //文件大小 int intFileSize = postedFile.ContentLength; //文件上传的文件夹目录(绝对路径) string strFolderMapPath = HttpContext.Current.Server.MapPath(filePath); //建立上传目录 if (!Directory.Exists(strFolderMapPath)) { Directory.CreateDirectory(strFolderMapPath); } //最终保存文件的路径(文件绝对路径+新生成的文件的新名称) string strFileMapPath = strFolderMapPath + "/" + fileName; //返回的文件虚拟目录(相对路径) string strFileUploadPath = filePath + "/" + fileName; oaiInfo.ErrorDescription = ""; //保存原图 try { postedFile.SaveAs(strFileMapPath); } catch (Exception ex) { oaiInfo.ErrorDescription = ex.Message; } //附件属性 oaiInfo.FileName = fileName; oaiInfo.FilePath = filePath; oaiInfo.FileUrl = strFileUploadPath; oaiInfo.FileSize = intFileSize; return oaiInfo; } #endregion # region 上传图片(图片byte[],自定义路径和名称) /// /// /// /// 图片byte /// 文件夹目录 /// 文件名 /// static public AttachmentInfo UploadImage(byte[] imgbytes, string filePath, string fileName) { AttachmentInfo oaiInfo = new AttachmentInfo(); //文件上传的文件夹目录(绝对路径) string strFolderMapPath = HttpContext.Current.Server.MapPath(filePath); //建立上传目录 if (!Directory.Exists(strFolderMapPath)) { Directory.CreateDirectory(strFolderMapPath); } //文件大小 int intFileSize = imgbytes.Length; //最终保存文件的路径(文件绝对路径+新生成的文件的新名称) string strFileMapPath = strFolderMapPath + "/" + fileName; //返回的文件虚拟目录(相对路径) string strFileUploadPath = filePath + "/" + fileName; oaiInfo.ErrorDescription = ""; using (MemoryStream ms = new MemoryStream(imgbytes)) { try { Bitmap bmp = new Bitmap(ms); Bitmap bmpnew = new Bitmap(bmp); bmp.Dispose(); bmp = null; bmpnew.Save(strFileMapPath, ImageFormat.Jpeg); bmpnew.Dispose(); } catch(Exception e) { oaiInfo.ErrorDescription = e.Message; } } oaiInfo.FileName = fileName; oaiInfo.FilePath = strFileMapPath; oaiInfo.FileUrl = strFileUploadPath; oaiInfo.FileSize = intFileSize; return oaiInfo; } #endregion #region 等比缩放图片 public static bool ResizeImage(Stream imageStream, string strSavePath, int width, int height) { bool blnRtn = false; try { //创建图片对象 System.Drawing.Image image, resizeimage; System.Drawing.Image.GetThumbnailImageAbort callb = null; //获得图片源 image = System.Drawing.Image.FromStream(imageStream); //计算图片的宽度和高度 double dobWidth = image.Width; double dobHeight = image.Height; //重新计算图片等比缩放后的宽度和高度(这里写的比较麻烦,你们看看又没有更好的办法) if (dobWidth > width || dobHeight > height) { if (dobWidth > dobHeight) { dobHeight = (int)(dobHeight * (width / dobWidth)); dobWidth = width; if (dobHeight > height) { dobWidth = (int)(dobWidth * (height / dobHeight)); dobHeight = height; } } else { dobWidth = (int)(dobWidth * (height / dobHeight)); dobHeight = height; if (dobWidth > width) { dobHeight = (int)(dobHeight * (width / dobWidth)); dobWidth = width; } } } else { } //缩放后图片 resizeimage = image.GetThumbnailImage((int)dobWidth, (int)dobHeight, callb, new System.IntPtr()); //保存图片 resizeimage.Save(strSavePath); //释放resizeimage对象的资源 image.Dispose(); //释放resizeimage对象的资源 resizeimage.Dispose(); blnRtn = true; //imageStream.Close(); //imageStream.Dispose(); } catch (Exception ex) { throw new Exception("ex:" + ex.Message); blnRtn = false; } return blnRtn; } #endregion #region 给图片加上水印 public static bool WaterImage(Stream imageStream, string strSavePath) { bool blnRtn = false; try { //获得图片源和水印图片源 System.Drawing.Image image = System.Drawing.Image.FromStream(imageStream); System.Drawing.Image imageWater = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("/watermark.png")); //根据图片源创建BitMap Bitmap bitmap = new Bitmap(image, image.Width, image.Height); Graphics g = Graphics.FromImage(bitmap); //计算画框的宽度高度以及位置 float rectWidth = imageWater.Width; float rectHeight = imageWater.Height; float rectX = image.Width - imageWater.Width; float rectY = image.Height - imageWater.Height; //加上水印 g.DrawImage(imageWater, rectX, rectY, rectWidth, rectHeight); //释放对象 image.Dispose(); imageWater.Dispose(); //保存图片 bitmap.Save(strSavePath, ImageFormat.Jpeg); //释放对象 g.Dispose(); bitmap.Dispose(); } catch { blnRtn = false; } return blnRtn; } #endregion #region 产生图片验证码 /// /// 产生图片验证码 /// /// public static void CreateCheckImage(string checkCode) { if ((checkCode != null) && !(checkCode.Trim() == string.Empty)) { Bitmap image = new Bitmap((int)Math.Ceiling((double)(checkCode.Length * 12.5)), 0x16); Graphics graphics = Graphics.FromImage(image); try { int num; Random random = new Random(); graphics.Clear(Color.White); for (num = 0; num < 0x19; num++) { int num2 = random.Next(image.Width); int num3 = random.Next(image.Width); int num4 = random.Next(image.Height); int num5 = random.Next(image.Height); graphics.DrawLine(new Pen(Color.Silver), num2, num4, num3, num5); } Font font = new Font("Arial", 12f, FontStyle.Italic | FontStyle.Bold); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); graphics.DrawString(checkCode, font, brush, (float)2f, (float)2f); for (num = 0; num < 100; num++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Gif); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ContentType = "image/Gif"; HttpContext.Current.Response.BinaryWrite(stream.ToArray()); } finally { graphics.Dispose(); image.Dispose(); } } } public byte[] CreateImage(string checkCode) { if (checkCode == null || checkCode.Trim() == string.Empty) return null; //生成BitMap图像 Bitmap image = new Bitmap((int)Math.Ceiling((double)(checkCode.Length * 12.5)), 0x16); Graphics graphics = Graphics.FromImage(image); try { int num; Random random = new Random(); graphics.Clear(Color.White); for (num = 0; num < 0x19; num++) { int num2 = random.Next(image.Width); int num3 = random.Next(image.Width); int num4 = random.Next(image.Height); int num5 = random.Next(image.Height); graphics.DrawLine(new Pen(Color.Silver), num2, num4, num3, num5); } Font font = new Font("Arial", 12f, FontStyle.Italic | FontStyle.Bold); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); graphics.DrawString(checkCode, font, brush, (float)2f, (float)2f); for (num = 0; num < 100; num++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //画图片的边框线 graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); //将图像保存到指定流 image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } finally { graphics.Dispose(); image.Dispose(); } } #endregion /// /// 根据地址图片宽和高 /// /// /// public static ImageInfo GetImageSize(string strImageUrl) { ImageInfo imageInfo = new ImageInfo(); strImageUrl = HttpContext.Current.Server.MapPath(strImageUrl); if (File.Exists(strImageUrl)) { Image imageOb = Image.FromFile(strImageUrl); imageInfo.Width = imageOb.Width; imageInfo.Height = imageOb.Height; } return imageInfo; } /// /// 根据地址图片高度 /// /// /// public static int GetImageHeight(string strImageUrl) { return GetImageSize(strImageUrl).Height; } // 影音快传图片地址 // 手机端域名为m.user.xxxx.cc,电脑端域名为my.xxxx.cc // 导致影音快传页面调用时缺省域名图片不显示,所以在上传时直接以绝对地址形式上传 public static string setImgUrl(string strImgUrl) { if (strImgUrl.Contains("&& strImgUrl.Contains("xxxx")) { return strImgUrl; } if (!strImgUrl.Contains("&& strImgUrl.Contains("xxxx")) { return "+ strImgUrl; } if (!strImgUrl.Contains("&& !strImgUrl.Contains("xxxx")) { return "+ strImgUrl; } return strImgUrl; } public static bool SaveImage(Stream imageStream, string strSavePath) { bool blnRtn = false; try { //创建图片对象 System.Drawing.Image image, resizeimage; System.Drawing.Image.GetThumbnailImageAbort callb = null; //获得图片源 image = System.Drawing.Image.FromStream(imageStream); image.Save(strSavePath); //释放resizeimage对象的资源 image.Dispose(); blnRtn = true; //imageStream.Close(); //imageStream.Dispose(); } catch (Exception ex) { //throw new Exception("ex:" + ex.Message); blnRtn = false; } return blnRtn; } #region 图片无损压缩 /// /// 无损压缩图片 /// /// 原图片地址 /// 压缩后保存图片地址 /// 压缩质量(数字越小压缩率越高)1-100 /// 压缩后图片的最大大小 /// 是否是第一次调用 /// public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true) { try { //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true FileInfo firstFileInfo = new FileInfo(sFile); if (sfsc == true && firstFileInfo.Length < size * 1024) { firstFileInfo.CopyTo(dFile, true); return true; } Image iSource = Image.FromFile(sFile); ImageFormat tFormat = iSource.RawFormat; int dHeight = iSource.Height / 2; int dWidth = iSource.Width / 2; int sW = 0, sH = 0; //按比例缩放 Size tem_size = new Size(iSource.Width, iSource.Height); if (tem_size.Width > dHeight || tem_size.Width > dWidth) { if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth)) { sW = dWidth; sH = (dWidth * tem_size.Height) / tem_size.Width; } else { sH = dHeight; sW = (tem_size.Width * dHeight) / tem_size.Height; } } else { sW = tem_size.Width; sH = tem_size.Height; } Bitmap ob = new Bitmap(dWidth, dHeight); Graphics g = Graphics.FromImage(ob); g.Clear(Color.WhiteSmoke); g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); g.Dispose(); //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径 FileInfo fi = new FileInfo(dFile); if (fi.Length > 1024 * size) { flag = flag - 10; CompressImage(sFile, dFile, flag, size, false); } } else { ob.Save(dFile, tFormat); } return true; } catch { return false; } finally { iSource.Dispose(); ob.Dispose(); } } catch { return false; } } #endregion }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:华为发声明:孟晚舟是无辜的,相信加拿大司法系统能作出同样结论!
下一篇:vue-cli 安装 2020最新 vue 4.0安装
相关文章

 发表评论

暂时没有评论,来抢沙发吧~