高质量图像缩放库[关闭]

2023-12-19

我想在 C# 中缩放图像,其质量级别与 Photoshop 一样好。有没有任何 C# 图像处理库可以完成这项工作?


这是一个注释良好的图像操作帮助器类,您可以查看和使用。我编写它作为如何在 C# 中执行某些图像处理任务的示例。您将会对以下内容感兴趣调整图像大小函数接受 System.Drawing.Image、宽度和高度作为参数。

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;

namespace DoctaJonez.Drawing.Imaging
{
    /// <summary>
    /// Provides various image untilities, such as high quality resizing and the ability to save a JPEG.
    /// </summary>
    public static class ImageUtilities
    {    
        /// <summary>
        /// A quick lookup for getting image encoders
        /// </summary>
        private static Dictionary<string, ImageCodecInfo> encoders = null;

        /// <summary>
        /// A lock to prevent concurrency issues loading the encoders.
        /// </summary>
        private static object encodersLock = new object();

        /// <summary>
        /// A quick lookup for getting image encoders
        /// </summary>
        public static Dictionary<string, ImageCodecInfo> Encoders
        {
            //get accessor that creates the dictionary on demand
            get
            {
                //if the quick lookup isn't initialised, initialise it
                if (encoders == null)
                {
                    //protect against concurrency issues
                    lock (encodersLock)
                    {
                        //check again, we might not have been the first person to acquire the lock (see the double checked lock pattern)
                        if (encoders == null)
                        {
                            encoders = new Dictionary<string, ImageCodecInfo>();

                            //get all the codecs
                            foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())
                            {
                                //add each codec to the quick lookup
                                encoders.Add(codec.MimeType.ToLower(), codec);
                            }
                        }
                    }
                }

                //return the lookup
                return encoders;
            }
        }

        /// <summary>
        /// Resize the image to the specified width and height.
        /// </summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="width">The width to resize to.</param>
        /// <param name="height">The height to resize to.</param>
        /// <returns>The resized image.</returns>
        public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
        {
            //a holder for the result
            Bitmap result = new Bitmap(width, height);
            //set the resolutions the same to avoid cropping due to resolution differences
            result.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            //use a graphics object to draw the resized image into the bitmap
            using (Graphics graphics = Graphics.FromImage(result))
            {
                //set the resize quality modes to high quality
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //draw the image into the target bitmap
                graphics.DrawImage(image, 0, 0, result.Width, result.Height);
            }

            //return the resulting bitmap
            return result;
        }

        /// <summary> 
        /// Saves an image as a jpeg image, with the given quality 
        /// </summary> 
        /// <param name="path">Path to which the image would be saved.</param> 
        /// <param name="quality">An integer from 0 to 100, with 100 being the 
        /// highest quality</param> 
        /// <exception cref="ArgumentOutOfRangeException">
        /// An invalid value was entered for image quality.
        /// </exception>
        public static void SaveJpeg(string path, Image image, int quality)
        {
            //ensure the quality is within the correct range
            if ((quality < 0) || (quality > 100))
            {
                //create the error message
                string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality.  A value of {0} was specified.", quality);
                //throw a helpful exception
                throw new ArgumentOutOfRangeException(error);
            }

            //create an encoder parameter for the image quality
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            //get the jpeg codec
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

            //create a collection of all parameters that we will pass to the encoder
            EncoderParameters encoderParams = new EncoderParameters(1);
            //set the quality parameter for the codec
            encoderParams.Param[0] = qualityParam;
            //save the image using the codec and the parameters
            image.Save(path, jpegCodec, encoderParams);
        }

        /// <summary> 
        /// Returns the image codec with the given mime type 
        /// </summary> 
        public static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            //do a case insensitive search for the mime type
            string lookupKey = mimeType.ToLower();

            //the codec to return, default to null
            ImageCodecInfo foundCodec = null;

            //if we have the encoder, get it to return
            if (Encoders.ContainsKey(lookupKey))
            {
                //pull the codec from the lookup
                foundCodec = Encoders[lookupKey];
            }

            return foundCodec;
        } 
    }
}

Update

有些人在评论中询问如何使用 ImageUtilities 类的示例,所以就在这里。

//resize the image to the specified height and width
using (var resized = ImageUtilities.ResizeImage(image, 50, 100))
{
    //save the resized image as a jpeg with a quality of 90
    ImageUtilities.SaveJpeg(@"C:\myimage.jpeg", resized, 90);
}

Note

请记住,图像是一次性的,因此您需要将调整大小的结果分配给using声明(或者您可以使用tryfinally并确保在finally中调用dispose)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

高质量图像缩放库[关闭] 的相关文章

  • 为什么这个 gif 的持续时间似乎是 0 毫秒?如何找到真实的持续时间?

    我正在尝试从动画 gif 文件中获取持续时间和帧数 以便计算 gif 的平均帧速率 然后将其转换为视频 我最近在测试过程中看到了这张图片 它似乎让一切都相信它的持续时间为 0 毫秒 为什么 如何找到真实的持续时间 到目前为止我已经尝试过 e
  • 捕获 .aspx 和 .ascx 页面中的异常

    问题说明了一切 请看以下示例代码 ul li li ul
  • 在 Mono 中反序列化 JSON 数据

    使用 Monodroid 时 是否有一种简单的方法可以将简单的 JSON 字符串反序列化为 NET 对象 System Json 只提供序列化 不提供反序列化 我尝试过的各种第三方库都会导致 Mono Monodroid 出现问题 谢谢 f
  • 2个对象,完全相同(除了命名空间)c#

    我正在使用第三方的一组网络服务 但遇到了一个小障碍 在我手动创建将每个属性从源复制到目标的方法之前 我想我应该在这里寻求更好的解决方案 我有 2 个对象 一个是 Customer CustomerParty 类型 另一个是 Appointm
  • 混合模型优先和代码优先

    我们使用模型优先方法创建了一个 Web 应用程序 一名新开发人员进入该项目 并使用代码优先方法 使用数据库文件 创建了一个新的自定义模型 这 这是代码第一个数据库上下文 namespace WVITDB DAL public class D
  • 为什么这个 makefile 在“make clean”上执行目标

    这是我当前的 makefile CXX g CXXFLAGS Wall O3 LDFLAGS TARGET testcpp SRCS main cpp object cpp foo cpp OBJS SRCS cpp o DEPS SRCS
  • Makefile 和 .Mak 文件 + CodeBlocks 和 VStudio

    我对整个 makefile 概念有点陌生 所以我对此有一些疑问 我正在 Linux 中使用 CodeBlocks 创建一个项目 我使用一个名为 cbp2mak 的工具从 CodeBlocks 项目创建一个 make 文件 如果有人知道更好的
  • if constexpr 中的 not-constexpr 变量 – clang 与 GCC

    struct A constexpr operator bool const return true int main auto f auto v if constexpr v A a f a clang 6 接受该代码 GCC 8 拒绝它
  • JavaScript 错误:MVC2 视图中的条件编译已关闭

    我试图在 MVC2 视图页面中单击时调用 JavaScript 函数 a href Select a JavaScript 函数 function SelectBenefit id code alert id alert code 这里 b
  • Linux 上的 RTLD_LOCAL 和dynamic_cast

    我们有一个由应用程序中的一些共享库构成的插件 我们需要在应用程序运行时更新它 出于性能原因 我们在卸载旧插件之前加载并开始使用新插件 并且只有当所有线程都使用旧插件完成后 我们才卸载它 由于新插件和旧插件的库具有相同的符号 我们dlopen
  • 在骨架图像中查找线 OpenCV python

    我有以下图片 我想找到一些线来进行一些计算 平均长度等 我尝试使用HoughLinesP 但它找不到线 我能怎么做 这是我的代码 sk skeleton mask rows cols sk shape imgOut np zeros row
  • 条件类型定义

    如果我有一小段这样的代码 template
  • MySQL 连接器 C++ 64 位在 Visual Studio 2012 中从源代码构建

    我正在尝试建立mySQL 连接器 C 从源头在视觉工作室2012为了64 bit建筑学 我知道这取决于一些boost头文件和C 连接器 跑步CMake生成一个项目文件 但该项目文件无法编译 因为有一大堆非常令人困惑的错误 这些错误可能与包含
  • 当Model和ViewModel一模一样的时候怎么办?

    我想知道什么是最佳实践 我被告知要始终创建 ViewModel 并且永远不要使用核心模型类将数据传递到视图 这就说得通了 让我把事情分开 但什么是Model 和ViewModel一模一样 我应该重新创建另一个类还是只是使用它 我觉得我应该重
  • 以编程方式创建 Blob 存储容器

    我有一个要求 即在创建公司时 在我的 storageaccount 中创建关联的 blob 存储容器 并将容器名称设置为传入的字符串变量 我已尝试以下操作 public void AddCompanyStorage string subDo
  • Xamarin Forms Binding - 访问父属性

    我无法访问页面的 ViewModel 属性以便将其绑定到 IsVisible 属性 如果我不设置 BindingContext 我只能绑定它 有没有办法可以在设置 BindingContext 的同时访问页面的 viewmodel root
  • C++ 指针引用混淆

    struct leaf int data leaf l leaf r struct leaf p void tree findparent int n int found leaf parent 这是 BST 的一段代码 我想问一下 为什么
  • 如何编写一个接受 int 或 float 的 C 函数?

    我想用 C 语言创建一个扩展 Python 的函数 该函数可以接受 float 或 int 类型的输入 所以基本上 我想要f 5 and f 5 5 成为可接受的输入 我认为我不能使用if PyArg ParseTuple args i v
  • 如何高效计算连续数的数字积?

    我正在尝试计算数字序列中每个数字的数字乘积 例如 21 22 23 98 99 将会 2 4 6 72 81 为了降低复杂性 我只会考虑 连续的数字 http simple wikipedia org wiki Consecutive in
  • 如何在 ASP.NET Core 中注入泛型的依赖关系

    我有以下存储库类 public class TestRepository Repository

随机推荐

  • 验证十进制数

    我正在阅读一些 csv 文件 其中包含表示十进制数的字符串 我的麻烦是 很多时候我接收使用不同区域设置的文件写入 例如 file1 csv的price列的值为129 13 是小数点分隔符 file1 csv的price列值为129 13 为
  • 如何计算密码学中的对数?

    我正在尝试对字节执行非线性函数来实现 SAFER 该算法需要计算字节的以 45 为底的对数 我不明白如何做到这一点 log45 201 1 39316393 当我将其分配给一个字节时 该值被截断为 1 并且我无法恢复确切的结果 我该怎么处理
  • 为什么这段 Javascript 代码这么慢?

    我有这段 Javascript 代码 在 Internet Explorer 中每次调用大约需要 600 毫秒 在其他浏览器中花费的时间可以忽略不计 var nvs currentTab var nvs zoomfield var nvs
  • 异步目录搜索器 (LDAP)

    我正在活动目录中执行长时间搜索 并且非常想使用 DirectorySearcher Asynchronous True 微软提供的文档很少MSDN http msdn microsoft com en us library system d
  • PHP 类:从被调用的方法访问调用实例

    很抱歉这个奇怪的话题 但我不知道如何用其他方式表达它 我正在尝试从调用类访问方法 就像这个例子一样 class normalClass public function someMethod this method shall access
  • Javascript/vue.js接收json

    我正在尝试在我的 vue js 应用程序中接收 json 如下所示 new Vue el body data role company list created function this getJson methods getJson f
  • 将对象重新放入 ConcurrentHashMap 是否会导致“发生在”内存关系?

    我正在与existing具有 ConcurrentHashMap 形式的对象存储的代码 映射内存储了可供多个线程使用的可变对象 根据设计 没有两个线程会尝试同时修改一个对象 我关心的是线程之间修改的可见性 目前 对象的代码在 setter
  • dojo multipleDefine与mapkitJS和ArcGIS esri-loader的错误

    我不知道在哪里MapkitJS and esri loader在一起有问题 从这里和其他地方的研究来看 似乎可能与另一个包存在命名冲突 这里有一个link https github com Esri esri loader issues 1
  • 在 v7 中使用 setViewCube 更新视图

    如何在 v7 中使用 setViewCube 更新视图 我在 v6 中使用了以下代码 但它在 v7 中不起作用 viewer setViewCube top front 在 v6 到 v7 的迁移指南中 它说 我应该通过扩展来调用它 ext
  • 如何在 UWP 应用中使用依赖注入?

    我在 UWP 应用程序中使用 autofac 在我的App例如 我正在设置依赖项 如下所示 public sealed partial class App private readonly IFacade m facade public A
  • 使用 AVAudioEngine 播放 AVAudioPCMBuffer 中的音频

    我有两节课MicrophoneHandler and AudioPlayer 我已经成功使用AVCaptureSession使用批准的答案窃听麦克风数据here https stackoverflow com questions 33850
  • ServiceStack 返回 JSV 而不是 JSON

    我有一个使用 ServiceStack 创建的服务 最近我更新了 ServiceStack 库 现在我收到的是 JSV 响应而不是 JSON 响应 该请求看起来像 POST http localhost api rest poll crea
  • 如何阻止用户在 XPages 中打开新的浏览器会话

    我有一个前端文档锁定过程 它创建一个包含 UNID 用户名 时间的应用程序范围变量 然后是一个每 30 秒更新此信息的计时器 如果有人尝试打开文档进行编辑 我会检查 使用 UNID 看看其他人是否拥有该文档 如果时间大于 30 秒 我会取消
  • 点击没有 jQuery UI 的 jQuery 弹跳效果

    我找不到仅使用 jQuery 动画来制作 div 弹跳的动画解决方案 类似的东西不起作用 bounce click function this effect bounce times 3 300 我不想使用 jQuery UI 或任何外部插
  • php正则表达式读取选择表单

    我有一个带有选择表单的源文件 其中包含一些选项 如下所示
  • 需要工作但导入不工作

    我有一个 actions js 文件正在导出这样的操作 export var toggleTodo id gt return type TOGGLE TODO id 但是当我使用 es6 import 导入它时出现错误 Uncaught T
  • 如何动态地将分支目标提示到 x64 CPU?

    我想知道如何用 C C 或汇编语言为 x64 处理器编写高效的跳转表 输入是预先已知的 但不可能通过算法来预测 假设我可以在输入流中查看尽可能远的位置 有什么方法可以动态地告诉 CPU 下一个分支将转到哪个地址 本质上 我想以编程方式更新分
  • 没有模板引擎的 Node.js

    我是 Node js 新手 正在尝试学习 据我了解 使用模板引擎 例如 Jade 是很常见的 甚至对于 CSS 例如 Stylus 也是如此 老实说 我见过的所有教程在布局方面都涉及模板引擎 问题是我不想使用模板引擎 因为我认为它不必要地复
  • javascript客户端到Python服务器:获取请求后XMLHttpRequest响应文本为空

    我正在尝试编写一个 chrome 扩展 它能够向 python 服务器脚本发送 接收数据 目前 我正处于 js 脚本发出 GET 请求的阶段 唯一的问题是 responseText 始终为空 即使 python 脚本以文本响应 popup
  • 高质量图像缩放库[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我想在 C 中缩放图像 其质量级别与 Photoshop 一样好 有没有任何 C 图像处理库可以完成这项工作 这是一个注释良好的图像操作帮