代码改变世界

在 .NET Core 下使用 SixLabors.ImageSharp 操作图片文件(放大、缩小、裁剪、加水印等等)的几个小示例

2019-09-19 14:53  音乐让我说  阅读(7722)  评论(5编辑  收藏  举报

1. 基础

1.1  将图片的宽度和高度缩小一半

直接贴代码了:

 

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="SixLabors.ImageSharp" Version="1.0.0-beta0007" />
  </ItemGroup>

  <ItemGroup>
    <None Update="foo.jpg">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

 

 

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Open the file and detect the file type and decode it.
        // Our image is now in an uncompressed, file format agnostic, structure in-memory as a series of pixels.
        using (Image image = Image.Load("foo.jpg"))
        {
            // Resize the image in place and return it for chaining.
            // 'x' signifies the current image processing context.
            image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2));

            // The library automatically picks an encoder based on the file extensions then encodes and write the data to disk.
            image.Save("bar.jpg");
        } // Dispose - releasing memory into a memory pool ready for the next image you wish to process.
    }
}

 

 1.2 以图片原始的格式保存文件

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System;
using System.Linq;
using System.Drawing.Text;

class Program
{
    static void Main(string[] args)
    {
        IImageFormat format;
        using (Image image = Image.Load("foo.jpg", out format))
        {
            image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2));
            image.Save($"bar.{format.FileExtensions.First()}");
        }
    }
}

 

 

1.3

 

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System;
using System.Linq;
using System.Drawing.Text;
using SixLabors.ImageSharp.Formats.Jpeg;

class Program
{
    static void Main(string[] args)
    {
        IImageFormat format;
        using (Image image = Image.Load("foo.jpg", out format))
        {
            image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2));
                JpegEncoder encoder = new JpegEncoder()
                {
                    //标准中定义的0到100之间的质量值。默认值为75。
                    //通过减少Quality松散的信息,从而减小文件大小。
                    Quality = 40,
                    //IgnoreMetadata = true
                };
                image.Save($"bar.{format.FileExtensions.First()}", encoder);
        }
    }
}

 

 

 

2. 进阶

2.1

 

3. 高级

3.1

 

谢谢浏览!