mirror of
https://github.com/aelurum/AssetStudio.git
synced 2025-05-25 05:40:21 -04:00
67 lines
2.2 KiB
C#
67 lines
2.2 KiB
C#
using SixLabors.ImageSharp;
|
|
using SixLabors.ImageSharp.Formats.Bmp;
|
|
using SixLabors.ImageSharp.Formats.Tga;
|
|
using SixLabors.ImageSharp.Formats.Webp;
|
|
using SixLabors.ImageSharp.PixelFormats;
|
|
using System;
|
|
using System.IO;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace AssetStudio
|
|
{
|
|
public static class ImageExtensions
|
|
{
|
|
public static void WriteToStream(this Image image, Stream stream, ImageFormat imageFormat)
|
|
{
|
|
switch (imageFormat)
|
|
{
|
|
case ImageFormat.Jpeg:
|
|
image.SaveAsJpeg(stream);
|
|
break;
|
|
case ImageFormat.Png:
|
|
image.SaveAsPng(stream);
|
|
break;
|
|
case ImageFormat.Bmp:
|
|
image.Save(stream, new BmpEncoder
|
|
{
|
|
BitsPerPixel = BmpBitsPerPixel.Pixel32,
|
|
SupportTransparency = true
|
|
});
|
|
break;
|
|
case ImageFormat.Tga:
|
|
image.Save(stream, new TgaEncoder
|
|
{
|
|
BitsPerPixel = TgaBitsPerPixel.Pixel32,
|
|
Compression = TgaCompression.None
|
|
});
|
|
break;
|
|
case ImageFormat.Webp:
|
|
image.Save(stream, new WebpEncoder
|
|
{
|
|
FileFormat = WebpFileFormatType.Lossless,
|
|
Quality = 50
|
|
});
|
|
break;
|
|
}
|
|
}
|
|
|
|
public static MemoryStream ConvertToStream(this Image image, ImageFormat imageFormat)
|
|
{
|
|
var stream = new MemoryStream();
|
|
image.WriteToStream(stream, imageFormat);
|
|
return stream;
|
|
}
|
|
|
|
public static byte[] ConvertToBytes<TPixel>(this Image<TPixel> image) where TPixel : unmanaged, IPixel<TPixel>
|
|
{
|
|
using (image)
|
|
{
|
|
Span<byte> imageSpan = new byte[image.Width * image.Height * 4];
|
|
image.CopyPixelDataTo(imageSpan);
|
|
|
|
return MemoryMarshal.AsBytes(imageSpan).ToArray();
|
|
}
|
|
}
|
|
}
|
|
}
|