C#——图片操作类简单封装

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using ReligionServer.constant;

namespace ReligionServer.util {

    /// <summary>
    /// 图片操作的工具类
    /// </summary>
    public class ImageUtil {

        /// <summary>
        /// Base64字符转图片单个存储: 将传入的Base64字符串image解析并转存到指定的target目录下, 返回FileInfo
        /// </summary>
        /// <param name="context"></param>
        /// <param name="image"></param>
        /// <returns></returns>
        public static Model.FileInfo Base64ImageInsert(HttpContext context, String image) {
            return ConvertBase64StringToImageAndInsert(context, image);
        }

        /// <summary>
        /// Base64字符转图片批量存储: 将传入的Base64字符串集合imageList解析并转存到指定的target目录下, 返回成功的FileInfo的List集合
        /// </summary>
        /// <param name="imageList"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public static List<Model.FileInfo> Base64ImageInsertBatch(HttpContext context, List<String> imageList) {
            List<Model.FileInfo> fileInfoList = new List<Model.FileInfo>();
            foreach (String item in imageList) {
                Model.FileInfo temp = Base64ImageInsert(context, item);
                if (temp != null) {
                    fileInfoList.Add(temp);
                }
            }
            return fileInfoList;
        }

        /// <summary>
        /// 将传入Base64字符串转换为BitMap并进行转存
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static Model.FileInfo ConvertBase64StringToImageAndInsert(HttpContext context, String value) {
            Model.FileInfo fileInfo = ParametersUtil.GetInstanceFormRequest<Model.FileInfo>(context, new Model.FileInfo());//使用ForeignKey初始化FileInfo
            if (!CommonUtil.IsEmpty(fileInfo.ForeignKey)) {
                MemoryStream memoryStream = null;
                Bitmap bitmap = null;
                try {
                    byte[] bytes = Convert.FromBase64String(parseBase64String(value));
                    String value_tmep = parseBase64String(value);
                    memoryStream = new MemoryStream(bytes);
                    bitmap = new Bitmap(memoryStream);
                    if (bitmap != null) {
                        String directory = DateUtil.CurrentDateTimeValue();//转存图片的文件夹
                        String targetPhysicalFilePath = context.Request.PhysicalApplicationPath + UploadConstant.UPLOAD_FILE_PATH + directory;//转存图片文件夹的物理路径
                        if (!Directory.Exists(targetPhysicalFilePath)) {
                            Directory.CreateDirectory(targetPhysicalFilePath);
                        }
                        String targetPath = targetPhysicalFilePath + "/" + CommonUtil.CreateFileName() + SuffixConstant.JPEG;//转存图片的全路径
                                                                                                                             //填充FileInfo
                        fileInfo.FileCode = CommonUtil.CreateId();
                        fileInfo.Name = CommonUtil.CreateFileName() + SuffixConstant.JPEG;
                        fileInfo.setType(SuffixConstant.JPEG.Substring(1));
                        fileInfo.Desc = parseBase64String(value);
                        fileInfo.Access = 0;//0表示关联, 1表示独立
                        fileInfo.Path = UploadConstant.UPLOAD_FILE_PATH + directory + "/" + CommonUtil.CreateFileName() + SuffixConstant.JPEG;
                        fileInfo.setCreateTime();
                        bitmap.Save(targetPath, System.Drawing.Imaging.ImageFormat.Png);
                        return fileInfo;
                    }
                } catch (Exception e) {
                    //暂时不做处理
                    System.Diagnostics.Debug.WriteLine(e.Message);
                } finally {
                    if (null != memoryStream) {
                        //GDI+ 中发生一般性错误, 这个问题一般为输出路径不存在, 或者是对当前输出路径没有权限, 再者就是文件的生命周期问题 这个问题如下所示
                        //在Image的整个操作过程中, memoryStream是不能关闭的, 只有等待Image的操作完毕后才可以关闭, 否则会出现 GDI+ 中发生一般性错误
                        //BitMap继承Image 
                        //百度解释:Bitmap 对象或一个 Image 对象从一个文件, 构造时该文件仍保留锁定对于对象的生存期。 因此, 无法更改图像并将其保存回它产生相同的文件
                        memoryStream.Close();
                    }
                    if (null != bitmap) {
                        //在Image操作完毕后, 回收Image所持有的资源
                        bitmap.Dispose();
                    }
                } 
            }
            return null;
        }

        /// <summary>
        /// 批量将传入的Base64字符串集合转为BitMap的List集合(暂时没有使用到)
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        private static List<Model.FileInfo> ConvertBase64StringToImageBatch(HttpContext context, List<String> values) {

            List<Model.FileInfo> fileInfoList = new List<Model.FileInfo>();
            if (values != null) {
                foreach (String item in values) {
                    fileInfoList.Add(ConvertBase64StringToImageAndInsert(context, item));
                }
            }
            return fileInfoList;
        }

        /// <summary>
        /// 对传入的Base64字符串进行一定的处理, 不然在做图片转换的时候会有影响
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static String parseBase64String(String value) {
            String result = String.Empty;//表示空字符串, 次字符串只读

            int index = value.IndexOf(",");

            result = value.Substring(index + 1, value.Length - index - 1);

            return result;
        }
    }
}

 

posted @ 2019-03-15 11:29  拂衣志  阅读(820)  评论(0编辑  收藏  举报