CSharp
using ImageProcessor;
using System;
using System.Drawing;
internal class WebpClass
{
public static (bool successful, Image image, string error) LoadPicture(string fileName)
{
try
{
using (ImageFactory pif = new ImageFactory())
{
var result = pif.Load(fileName);
if (result.Image != null)
{
return (true, new Bitmap(pif.Load(fileName).Image), null);
}
else
{
return (false, null, "读取失败!");
}
}
}
catch (Exception ex)
{
return (false, null, ex.Message);
}
}
public static (bool successful, string error) SaveWebp(string fileName, Image img, int quality = 100)
{
try
{
using (ImageFactory pif = new ImageFactory())
{
pif.Load(img);
pif.PreserveExifData = true;
pif.Format(new ImageProcessor.Plugins.WebP.Imaging.Formats.WebPFormat() { Quality = quality <= 50 ? 50 : quality });
pif.Save(fileName);
return (true, null);
}
}
catch (Exception ex)
{
return (false, ex.Message);
}
}
}
VB.NET
Imports ImageProcessor
Public Class webp
''' <summary>
''' 将输入的图像保存为webp图像。
''' </summary>
''' <param name="fn"></param>
''' <param name="img"></param>
''' <param name="quality"></param>
''' <returns></returns>
Shared Function SaveWebp(fn As String, img As Image, Optional quality As Integer = 100) As Boolean
Try
Using ipf As New ImageFactory
ipf.Load(img)
ipf.PreserveExifData = False
ipf.Format(New Plugins.WebP.Imaging.Formats.WebPFormat() With {.Quality = If(quality <= 50, 50, quality)})
ipf.Save(fn)
Return True
End Using
Catch ex As Exception
'MessageBox.Show($"保存webp失败!{ex.Message}", "webp", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return False
End Try
End Function
''' <summary>
''' 读取指定文件名的文件,返回图像。
''' </summary>
''' <param name="fn"></param>
''' <returns></returns>
Shared Function Load(fn As String) As Image
Try
Using pif As New ImageFactory
Return New Bitmap(pif.Load(fn).Image)
End Using
Catch ex As Exception
'MessageBox.Show($"保存webp失败!{ex.Message}", "webp", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return Nothing
End Try
End Function
End Class