ImageResizer上传图片,并批量切割不同大小的图片

本文介绍了一个使用C#实现的图片上传和处理方法,该方法能够接收上传的图片文件,并自动生成多种尺寸的缩略图,包括正方形缩略图、中等尺寸和大尺寸的图片。通过定义不同版本的图片规格,可以灵活地适应各种应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

具体看官方demo,下面是测试代码

using ImageResizer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    /// <summary>
    /// getimg 的摘要说明
    /// </summary>
    public class getimg : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var ctxfiles = HttpContext.Current.Request.Files;
            if (ctxfiles == null) return;

            //Define the versions to generate
            Dictionary<string, string> versions = new Dictionary<string, string>();
            versions.Add("_thumb", "width=100&height=100&crop=auto&format=jpg"); //Crop to square thumbnail
            versions.Add("_medium", "maxwidth=400&maxheight=400&format=jpg"); //Fit inside 400x400 area, jpeg
            versions.Add("_large", "maxwidth=1900&maxheight=1900&format=jpg"); //Fit inside 1900x1200 area

            foreach (string fileKey in ctxfiles.Keys)
            {
                HttpPostedFile file = ctxfiles[fileKey];
                if (file.ContentLength <= 0)
                    continue;

                string uploadFolder = context.Server.MapPath("~/uploads");
                if (!Directory.Exists(uploadFolder))
                    Directory.CreateDirectory(uploadFolder);

                //Generate each version
                foreach (string suffix in versions.Keys)
                {
                    string fileName = Path.Combine(uploadFolder, Guid.NewGuid().ToString() + suffix);
                    ImageJob i = new ImageJob(file,
                        "~/uploads/<guid>.<ext>",
                        new Instructions(versions[suffix]),
                        false,
                        true
                    );
                    fileName = ImageBuilder.Current.Build(i).FinalPath;
                    //...
                }
            }

            context.Response.Write("img upload success!");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值