重写HttpPostedFileBase 图片压缩

遇到一个场景    文件操作模块是其他同事编写 直接通过HttpPostedFileBase来保存图片 这边不能动原来的上传流程  原来上传的图片都是没有经过压缩  导致APP加载速度会很慢

图片压缩代码

参考自:https://github.com/zkweb-framework/ZKWeb/blob/master/ZKWeb/ZKWebStandard/Extensions/ImageExtensions.cs

using MyCompanyName.Extensions.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompanyName.Extensions.Extensions
{
    public static class ImageExtensions
    {

        /// <summary>
        /// Resize image
        /// </summary>
        /// <param name="image">Original image</param>
        /// <param name="width">Width</param>
        /// <param name="height">height</param>
        /// <param name="mode">Resize mode</param>
        /// <param name="background">Background default is transparent</param>
        /// <returns></returns>
        public static Image Resize(this Image image,
            int width, int height, ImageResizeMode mode, Color? background = null)
        {
            var src = new Rectangle(0, 0, image.Width, image.Height);
            var dst = new Rectangle(0, 0, width, height);
            // Calculate destination rectangle by resize mode
            if (mode == ImageResizeMode.Fixed)
            {
            }
            else if (mode == ImageResizeMode.ByWidth)
            {
                height = (int)((decimal)src.Height / src.Width * dst.Width);
                dst.Height = height;
            }
            else if (mode == ImageResizeMode.ByHeight)
            {
                width = (int)((decimal)src.Width / src.Height * dst.Height);
                dst.Width = width;
            }
            else if (mode == ImageResizeMode.Cut)
            {
                if ((decimal)src.Width / src.Height > (decimal)dst.Width / dst.Height)
                {
                    src.Width = (int)((decimal)dst.Width / dst.Height * src.Height);
                    src.X = (image.Width - src.Width) / 2; // Cut left and right
                }
                else
                {
                    src.Height = (int)((decimal)dst.Height / dst.Width * src.Width);
                    src.Y = (image.Height - src.Height) / 2; // Cut top and bottom
                }
            }
            else if (mode == ImageResizeMode.Padding)
            {
                if ((decimal)src.Width / src.Height > (decimal)dst.Width / dst.Height)
                {
                    dst.Height = (int)((decimal)src.Height / src.Width * dst.Width);
                    dst.Y = (height - dst.Height) / 2; // Padding left and right
                }
                else
                {
                    dst.Width = (int)((decimal)src.Width / src.Height * dst.Height);
                    dst.X = (width - dst.Width) / 2; // Padding top and bottom
                }
            }
            // Draw new image
            var newImage = new Bitmap(width, height);
            using (var graphics = Graphics.FromImage(newImage))
            {
                // Set smoothing mode
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                // Set background color
                graphics.Clear(background ?? Color.Transparent);
                // Render original image with the calculated rectangle
                graphics.DrawImage(image, dst, src, GraphicsUnit.Pixel);
            }
            return newImage;
        }

        /// <summary>
        /// Save to jpeg with specified quality
        /// </summary>
        /// <param name="image">Image object</param>
        /// <param name="filename">File path, will automatic create parent directories</param>
        /// <param name="quality">Compress quality, 1~100</param>
        public static void SaveJpeg(this Image image, string filename, long quality)
        {
            PathUtils.EnsureParentDirectory(filename);
            var encoder = ImageCodecInfo.GetImageEncoders().First(
                c => c.FormatID == ImageFormat.Jpeg.Guid);
            var parameters = new EncoderParameters();
            parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            image.Save(filename, encoder, parameters);
        }

        /// <summary>
        /// Save to icon, see
        /// http://stackoverflow.com/questions/11434673/bitmap-save-to-save-an-icon-actually-saves-a-png
        /// </summary>
        /// <param name="image">Image object</param>
        /// <param name="filename">File path, will automatic create parent directories</param>
        public static void SaveIcon(this Image image, string filename)
        {
            PathUtils.EnsureParentDirectory(filename);
            using (var stream = new FileStream(filename, FileMode.Create))
            {
                // Header (ico, 1 photo)
                stream.Write(new byte[] { 0, 0, 1, 0, 1, 0 }, 0, 6);
                // Size
                stream.WriteByte(checked((byte)image.Width));
                stream.WriteByte(checked((byte)image.Height));
                // No palette
                stream.WriteByte(0);
                // Reserved
                stream.WriteByte(0);
                // No color planes
                stream.Write(new byte[] { 0, 0 }, 0, 2);
                // 32 bpp
                stream.Write(new byte[] { 32, 0 }, 0, 2);
                // Image data length, set later
                stream.Write(new byte[] { 0, 0, 0, 0 }, 0, 4);
                // Image data offset, fixed 22 here
                stream.Write(new byte[] { 22, 0, 0, 0 }, 0, 4);
                // Write png data
                image.Save(stream, ImageFormat.Png);
                // Write image data length
                long imageSize = stream.Length - 22;
                stream.Seek(14, SeekOrigin.Begin);
                stream.WriteByte((byte)(imageSize));
                stream.WriteByte((byte)(imageSize >> 8));
                stream.WriteByte((byte)(imageSize >> 16));
                stream.WriteByte((byte)(imageSize >> 24));
            }
        }

        /// <summary>
        /// Save image by it‘s file extension
        /// Quality parameter only available for jpeg
        /// </summary>
        /// <param name="image">Image object</param>
        /// <param name="filename">File path, will automatic create parent directories</param>
        /// <param name="quality">Compress quality, 1~100</param>
        public static void SaveAuto(this Image image, string filename, long quality)
        {
            PathUtils.EnsureParentDirectory(filename);
            var extension = Path.GetExtension(filename).ToLower();
            if (extension == ".jpg" || extension == ".jpeg")
            {
                image.SaveJpeg(filename, quality);
            }
            else if (extension == ".bmp")
            {
                image.Save(filename, ImageFormat.Bmp);
            }
            else if (extension == ".gif")
            {
                image.Save(filename, ImageFormat.Gif);
            }
            else if (extension == ".ico")
            {
                image.SaveIcon(filename);
            }
            else if (extension == ".png")
            {
                image.Save(filename, ImageFormat.Png);
            }
            else if (extension == ".tiff")
            {
                image.Save(filename, ImageFormat.Tiff);
            }
            else if (extension == ".exif")
            {
                image.Save(filename, ImageFormat.Exif);
            }
            else
            {
                throw new NotSupportedException(
                    string.Format("unsupport image extension {0}", extension));
            }
        }
    }

    /// <summary>
    /// Image resize mode
    /// </summary>
    public enum ImageResizeMode
    {
        /// <summary>
        /// Resize to the specified size, allow aspect ratio change
        /// </summary>
        Fixed,
        /// <summary>
        /// Resize to the specified width, height is calculated by the aspect ratio
        /// </summary>
        ByWidth,
        /// <summary>
        /// Resize to the specified height, width is calculated by the aspect ratio
        /// </summary>
        ByHeight,
        /// <summary>
        /// Resize to the specified size, keep aspect ratio and cut the overflow part
        /// </summary>
        Cut,
        /// <summary>
        /// Resize to the specified size, keep aspect ratio and padding the insufficient part
        /// </summary>
        Padding
    }
}

  重写HttpPostedFileBase

using MyCompanyName.Extensions.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace MyCompanyName.Extensions.Web.Http
{
    public class ImageHttpPostedFileBase : HttpPostedFileBase
    {
        Stream stream;
        string contentType;
        string fileName;
        public int ImageQuality { get; set; }
        public Size ImageThumbnailSize { get; set; }
        public ImageResizeMode ImageResizeMode { get; set; }
        public ImageHttpPostedFileBase(Stream stream, string contentType, string fileName, Size imageThumbnailSize, int ImageQuality, ImageResizeMode imageResizeMode)
        {
            this.stream = stream;
            this.contentType = contentType;
            this.fileName = fileName;
            this.ImageQuality = ImageQuality;
            this.ImageThumbnailSize = imageThumbnailSize;
            this.ImageResizeMode = imageResizeMode;

        }

        public override int ContentLength
        {
            get { return (int)stream.Length; }
        }

        public override string ContentType
        {
            get { return contentType; }
        }

        public override string FileName
        {
            get { return fileName; }
        }

        public override Stream InputStream
        {
            get { return stream; }
        }

        public override void SaveAs(string filename)
        {
            var image = Image.FromStream(stream);
            using (var thumbnailImage = image.Resize(ImageThumbnailSize.Width, ImageThumbnailSize.Height, ImageResizeMode, Color.White))
                thumbnailImage.SaveAuto(filename, ImageQuality);

        }

    }
}

  重写HttpPostedFileBase加入了一些自定义的属性 SoEasy

ImageHttpPostedFileBase fileBase = new ImageHttpPostedFileBase(file.InputStream, file.ContentType, file.FileName, new Size(800, 800), 90, Extensions.Extensions.ImageResizeMode.ByWidth);

  

时间: 2024-10-03 14:41:50

重写HttpPostedFileBase 图片压缩的相关文章

Html5+asp.net mvc 图片压缩上传

在做图片上传时,大图片如果没有压缩直接上传时间会非常长,因为有的图片太大,传到服务器上再压缩太慢了,而且损耗流量. 思路是将图片抽样显示在canvas上,然后用通过canvas.toDataURL方法得到base64字符串来实现压缩. 废话不多少不多说直接看代码: 本次测试使用了 zepto.min.js 插件,更新版本的下载请点击这里 主要js代码: //图片压缩处理 ; (function () { /** * 加载的时候进行抽样检测 * 在iOS中,大于2M的图片会抽样渲染 */ func

Android webview实现上传图片的效果(图片压缩)

mainactivity代码 package com.bwie.webviewupload; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.text.SimpleDateFormat; import

java 图片压缩变色问题

java图片压缩,有时由于图片自身的原因,如透明的PNG图.改alpha通道或四色图等. 压缩完了,会出现图片变色的情况. 如: 原图 压缩完: 尝试了很多方法,如JDK原生的方式及第三方组件java-image-scaling或thumbnailator都不解决问题. 后来采用阿里的SimpleImage解决.记录一下 SimpleImage github地址:https://github.com/alibaba/simpleimage依赖jar:commons-io-2.4.jarcommo

iOS开发探索-图片压缩处理

介绍: 压: 指文件体积变小,但是像素数不变,长宽尺寸不变,那么质量可能下降.缩: 指文件的尺寸变小,也就是像素数减少,而长宽尺寸变小,文件体积同样会减小. 应用: 在实际开发中,我们经常会对图片进行处理,满足开发需求,以下介绍三种图片压缩处理: 1.压缩图片质量(图片体积减小,像素不变) 两种读取图片数据的简单方法:(1).UIImageJPEGRepresentation函数需要两个参数:图片的引用和压缩系数,压缩体积不是随压缩系数比例变化的.(2).UIImagePNGRepresenta

CxImager图片压缩助手v1.1免费版[下载]

CxImager图片压缩助手v1.1运行环境:WinXP/2003/Vista/Win2008/Win7软件版本:1.1软件大小:1.37M软件语言:简体中文软件类型:系统工具授权方式:免费版推荐星级:★★★★★ 修改时间: 2015年10月25日 12:38:28 MD5: 634F21AB6109A59F3A1DCC5AFA2F7F5A SHA1: 1AAA0E18AB20650DB3B4E846EA3F6FB7FDEEA7C0 CRC32: 00F6A62B 下载地址: 软件简介:   C

图片压缩的在线好工具

上周日参加了前端圈的一个走进名企腾讯专场的活动,在会议上有分享嘉宾谈到一个图片的压缩网址,当时也并未太放在心上,没想到本周就接了一个新项目,里面用到的图片都是那种大图,PNG居多,而领导又再三强调一定要保证网页的加载速度,当时就想到那次活动上分享的一个在线压缩工具,于是百度一搜图片压缩工具,发现一个在线图片压缩软件https://tinypng.com/,抱着试试的心态,上传了一张图片开始进行压缩,竟然图片小了一半多,而且图片质量损耗也不明显,果断把用到的图片都往上压了一次,同时发现这个工具对于

每日总结 - 图片压缩

利用android系统压缩方式进行图片压缩,代码: 1 private String path = "/sdcard/img.jpg"; 2 File f = new File(path); 3 Bitmap bm = PictureUtil.getSmallBitmap(this,path); 4 FileOutputStream fos; 5 try { 6 fos = new FileOutputStream(new File("/sdcard/", &quo

spring mvc 图片上传,图片压缩、跨域解决、 按天生成目录 ,删除,限制为图片代码等相关配置

spring mvc 图片上传,跨域解决 按天生成目录 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ #fs.domains=182=http://172.16.100.182:18080,localhost=http://localhost:8080 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE be

(转)Android学习-使用Async-Http实现图片压缩并上传功能

(转)Android学习-使用Async-Http实现图片压缩并上传功能 文章转载自:作者:RyaneLee链接:http://www.jianshu.com/p/940fc7ba39e1 让我头疼一个星期的图片批量上传服务器的问题最后受这篇文章的作者启发而解决,自己之前一直执着于通过uri地址找到图片然后上传图片,却没想过直接上传图片本身.感谢作者的博客和启发. 前言 (转载请注明出处,谢谢!) 最近在做一个小项目,项目中要实现上传图片到服务器,而这个例子是实现图片的尺寸压缩,将获取到的压缩图