Common下ImageHelper.cs

本文介绍了一种生成图片缩略图的方法及图片上传的具体实现。包括如何根据不同的需求调整缩略图尺寸,确保图片质量的同时减少加载时间。此外,还详细说明了文件上传过程中的路径处理、格式验证等关键步骤。

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

namespace Common
{
    public class ImageHelper:Page
    {
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>   
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放(可能变形)               
                    break;
                case "W"://指定宽,高按比例                   
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减(不变形)               
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        private string upimg(FileUpload up,string oldimgurl)
        {
            string result = "";
            if (up.HasFile)
            {
                string fileContentType = up.PostedFile.ContentType;
                if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg" || fileContentType == "image/jpeg" || fileContentType == "image/x-png")
                {
                    string ImgFileName = DateTime.Now.ToString("yyyyMMddHHmmss");//该商品图片存放文件夹名称
                    string fileName = ImgFileName + ".jpg"; // 文件名称 
                    string JueDuiUrl = Server.MapPath("~/proimages");
                    string xiangduiurl = "~/proimages" + "/" + fileName;

                    if (!Directory.Exists(JueDuiUrl))
                    {
                        Directory.CreateDirectory(JueDuiUrl);//如果不存在,则创建
                    }
                    string webFilePath = JueDuiUrl + "//" + fileName;        // 服务器端文件路径  
                    if (!File.Exists(webFilePath))
                    {
                        if (!string.IsNullOrEmpty(oldimgurl))
                        {
                            new Common.FileHelper().DeleteImg(oldimgurl);
                        }
                        up.SaveAs(webFilePath);
                        result = xiangduiurl;
                    }
                }
                else
                {
                    Common.MessageBox.Show(Page, "请选择正确图片格式");
                    return "";
                }
            }
            return result;
        }
    }
}

1. Vision.Data.Models.dll - 数据模型和接口 text Vision.Data.Models.dll/ ├── Models/ # 数据模型类 │ ├── InspectionResult.cs # 检测结果模型 │ ├── CameraInfo.cs # 相机信息模型 │ ├── Recipe.cs # 检测配方模型 │ ├── SystemConfig.cs # 系统配置模型 │ ├── AlgorithmResult.cs # 算法结果模型 │ ├── DeviceStatus.cs # 设备状态模型 │ └── LogEntry.cs # 日志条目模型 │ ├── Interfaces/ # 接口定义 │ ├── IVisionAlgorithm.cs # 算法通用接口 │ ├── ILogger.cs # ✅ 日志接口 │ ├── IConfigurable.cs # 可配置接口 │ ├── IInitializable.cs # 可初始化接口 │ └── IDisposableResource.cs # 资源释放接口 │ ├── Enums/ # 枚举定义 │ ├── DeviceType.cs # 设备类型枚举 │ ├── InspectionStatus.cs # 检测状态枚举 │ ├── ErrorCodes.cs # 错误代码枚举 │ ├── TriggerMode.cs # 触发模式枚举 │ └── LogLevel.cs # ✅ 日志级别枚举 │ └── Events/ # 事件参数 ├── ImageGrabbedEventArgs.cs # 图像采集事件 ├── InspectionCompletedEventArgs.cs # 检测完成事件 └── DeviceStatusChangedEventArgs.cs # 设备状态变化事件 2. Vision.Device.Interfaces.dll - 设备驱动接口 text Vision.Device.Interfaces.dll/ ├── Camera/ # 相机接口 │ ├── ICamera.cs # 相机主接口 │ ├── ICameraInfo.cs # 相机信息接口 │ └── ICameraAsync.cs # 相机异步接口 │ ├── Light/ # 光源接口 │ ├── ILightController.cs # 光源控制器接口 │ └── ISerialLight.cs # 串口光源接口 │ ├── IO/ # IO接口 │ ├── IIOController.cs # IO控制器接口 │ └── ICommunication.cs # 通信接口 │ ├── Common/ # 通用设备接口 │ ├── IDevice.cs # 设备基础接口 │ ├── IConnectable.cs # 可连接接口 │ ├── IConfigurableDevice.cs # 可配置设备接口 │ └── IDeviceStatus.cs # 设备状态接口 │ └── Exceptions/ # 异常类 ├── DeviceException.cs # 设备异常基类 ├── CameraException.cs # 相机异常 └── ConnectionException.cs # 连接异常 3. Vision.Core.dll - 核心引擎(包含日志实现) text Vision.Core.dll/ ├── Engine/ # 引擎核心 │ ├── VisionEngine.cs # 视觉引擎主类 │ ├── DeviceManager.cs # 设备管理器 │ └── AlgorithmExecutor.cs # 算法执行器 │ ├── Services/ # 核心服务 │ ├── ConfigManager.cs # 配置管理服务 │ ├── RecipeManager.cs # 配方管理服务 │ ├── InspectionService.cs # 检测流程服务 │ └── DataService.cs # 数据服务 │ ├── Utilities/ # 工具类(✅包含日志实现) │ ├── Logger.cs # ✅ 日志系统实现 │ ├── FileLogWriter.cs # ✅ 文件日志写入器 │ ├── ConsoleLogWriter.cs # ✅ 控制台日志写入器 │ ├── PluginLoader.cs # 插件加载器 │ ├── ImageHelper.cs # 图像工具类 │ └── ExtensionMethods.cs # 扩展方法 │ └── Events/ # 事件处理 ├── VisionEventArgs.cs # 事件参数基类 ├── DeviceEventArgs.cs # 设备事件参数 └── InspectionEventArgs.cs # 检测事件参数 4. 设备驱动DLL结构 Vision.Device.Camera.Hik.dll - 海康相机 text Vision.Device.Camera.Hik.dll/ ├── HikCamera.cs # 海康相机实现类 ├── HikCameraInfo.cs # 海康相机信息类 ├── HikSDKWrapper.cs # 海康SDK封装类 └── HikConstants.cs # 海康常量定义 Vision.Device.Camera.HalconGeneric.dll - Halcon通用相机 text Vision.Device.Camera.HalconGeneric.dll/ ├── HalconGenericCamera.cs # Halcon通用相机实现 ├── HalconAcquisition.cs # Halcon采集封装 ├── CameraDiscoverer.cs # 相机发现类 └── HalconConversion.cs # Halcon转换工具 Vision.Device.Light.Serial.dll - 串口光源 text Vision.Device.Light.Serial.dll/ ├── SerialLightController.cs # 串口光源控制器 ├── LightProtocol.cs # 光源通信协议 ├── CommandBuilder.cs # 命令构建器 └── SerialPortManager.cs # 串口管理 5. 算法模块DLL结构 Vision.Algorithms.Base.dll - 基础算法 text Vision.Algorithms.Base.dll/ ├── BasicAlgorithms.cs # 基础算法主类 ├── ImageProcessing/ # 图像处理算法 │ ├── ThresholdAlgorithm.cs # 二值化算法 │ ├── FilterAlgorithm.cs # 滤波算法 │ └── MorphologyAlgorithm.cs # 形态学算法 │ ├── Measurement/ # 测量算法 │ ├── EdgeDetection.cs # 边缘检测 │ ├── CaliperTool.cs # 卡尺工具 │ └── CircleFitting.cs # 圆拟合 │ ├── Recognition/ # 识别算法 │ ├── BarcodeReader.cs # 条码识别 │ ├── QRCodeReader.cs # 二维码识别 │ └── OCRBasic.cs # 基础OCR │ └── Analysis/ # 分析算法 ├── BlobAnalyzer.cs # 斑点分析 ├── ColorAnalysis.cs # 颜色分析 └── StatisticalAnalysis.cs # 统计分析 Vision.Algorithms.Advanced.dll - 高级算法接口 text Vision.Algorithms.Advanced.dll/ ├── Interfaces/ # 高级算法接口 │ ├── IAdvancedAlgorithm.cs # 高级算法接口 │ ├── ITrainableAlgorithm.cs # 可训练算法接口 │ └── IModelBasedAlgorithm.cs # 基于模型的算法接口 │ ├── Models/ # 算法模型 │ ├── AlgorithmParameters.cs # 算法参数模型 │ ├── TrainingData.cs # 训练数据模型 │ └── ModelInfo.cs # 模型信息 │ ├── Management/ # 算法管理 │ ├── AlgorithmExecutor.cs # 算法执行器 │ ├── PluginManager.cs # 插件管理器 │ └── ModelManager.cs # 模型管理器 │ └── Utilities/ # 算法工具 ├── AlgorithmHelper.cs # 算法工具类 ├── ValidationHelper.cs # 验证工具类 └── PerformanceMonitor.cs # 性能监控 这样看呢
最新发布
11-07
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值