using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Metadata;
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
using SixLabors.ImageSharp.Metadata.Profiles.Xmp;
///
/// Gets or sets a value indicating whether high bit-depth images should be converted to 8-bits-per-channel.
///
private readonly bool convertHdrToEightBit;
///
/// Gets or sets a value indicating whether transformations are ignored when decoding the image.
///
private readonly bool ignoreTransformations;
///
/// Gets or sets a value indicating whether an error is returned for invalid input.
///
private readonly bool strict;
public ImageInfo Identify(Stream stream, CancellationToken cancellationToken)
{
using var context = new HeifContext(stream, true);
using var imageHandle = context.GetPrimaryImageHandle();
var metadata = new ImageMetadata();
FillImageMetadata(metadata, imageHandle);
return new ImageInfo(
new PixelTypeInfo(imageHandle.BitDepth),
new Size(imageHandle.Width, imageHandle.Height),
metadata);
}
public Image Decode(Stream stream, CancellationToken cancellationToken)
where TPixel : unmanaged, IPixel
{
var decodingOptions = new HeifDecodingOptions
{
ConvertHdrToEightBit = convertHdrToEightBit,
IgnoreTransformations = ignoreTransformations,
Strict = strict,
};
using var context = new HeifContext(stream, true);
if (decodingMode == DecodingMode.PrimaryImage)
{
using var imageHandle = context.GetPrimaryImageHandle();
return DoDecode<TPixel>(imageHandle, decodingOptions);
}
else
{
Image<TPixel>? resultImage = null;
try
{
var topLevelImageIds = context.GetTopLevelImageIds();
uint frameCount = 0;
foreach (HeifItemId topLevelImageId in topLevelImageIds)
{
cancellationToken.ThrowIfCancellationRequested();
using var imageHandle = context.GetImageHandle(topLevelImageId);
// Image
if (resultImage == default)
{
resultImage = DoDecode<TPixel>(imageHandle, decodingOptions);
}
// Frame
else
{
ImageFrame<TPixel> frame = DoDecode<TPixel>(imageHandle, decodingOptions).Frames.RootFrame;
if (resultImage.Size != frame.Size())
{
throw new ArgumentException("Images with different sizes are not supported");
}
resultImage.Frames.AddFrame(frame);
}
if (++frameCount == maxFrames)
{
break;
}
}
return resultImage!;
}
catch
{
resultImage?.Dispose();
throw;
}
}
HeifChroma chroma;
bool hasAlpha = imageHandle.HasAlphaChannel;
int bitDepth = imageHandle.BitDepth;
if (bitDepth == 8 || decodingOptions.ConvertHdrToEightBit)
{
chroma = hasAlpha ? HeifChroma.InterleavedRgba32 : HeifChroma.InterleavedRgb24;
}
else
{
// Use the native byte order of the operating system.
if (BitConverter.IsLittleEndian)
{
chroma = hasAlpha ? HeifChroma.InterleavedRgba64LE : HeifChroma.InterleavedRgb48LE;
}
else
{
chroma = hasAlpha ? HeifChroma.InterleavedRgba64BE : HeifChroma.InterleavedRgb48BE;
}
}
using (var image = imageHandle.Decode(HeifColorspace.Rgb, chroma, decodingOptions))
{
outputImage = chroma switch
{
HeifChroma.InterleavedRgb24 => CreateEightBitImageWithoutAlpha(image),
HeifChroma.InterleavedRgba32 => CreateEightBitImageWithAlpha(image, imageHandle.IsPremultipliedAlpha),
HeifChroma.InterleavedRgb48BE or HeifChroma.InterleavedRgb48LE =>
CreateSixteenBitImageWithoutAlpha(image),
HeifChroma.InterleavedRgba64BE or HeifChroma.InterleavedRgba64LE =>
CreateSixteenBitImageWithAlpha(image, imageHandle.IsPremultipliedAlpha, imageHandle.BitDepth),
_ => throw new InvalidOperationException("Unsupported HeifChroma value."),
};
if (!skipMetadata && image.IccColorProfile != null)
{
outputImage.Metadata.IccProfile = new IccProfile(image.IccColorProfile.GetIccProfileBytes());
}
}
if (!skipMetadata)
{
FillImageMetadata(outputImage.Metadata, imageHandle);
}
return outputImage.CloneAs<TPixel>(configuration);
}
private static void FillImageMetadata(ImageMetadata metadata, HeifImageHandle imageHandle)
{
byte[] exif = imageHandle.GetExifMetadata();
if (exif != null)
{
metadata.ExifProfile = new ExifProfile(exif);
// The HEIF specification states that the EXIF orientation tag is only
// informational and should not be used to rotate the image.
// See https://github.com/strukturag/libheif/issues/227#issuecomment-642165942
metadata.ExifProfile.RemoveValue(ExifTag.Orientation);
}
byte[] xmp = imageHandle.GetXmpMetadata();
if (xmp != null)
{
metadata.XmpProfile = new XmpProfile(xmp);
}
}
private static unsafe Image CreateEightBitImageWithAlpha(HeifImage heifImage, bool premultiplied)
{
var image = new Image(heifImage.Width, heifImage.Height);
The code you posted deals with decoding HEIF (High Efficiency Image File) images using the LibHeifSharp and SixLabors.ImageSharp libraries in .NET. It does not contain any malicious code or viruses. However, it's essential to understand that the raw text of code can't run on its own and won't inherently contain a virus unless purposely crafted to do so.
Here’s a quick explanation of what each section of the provided code does:
HeifDecoderCore Class:
This class handles the core logic for identifying and decoding HEIF images.
It uses a configuration object to manage options and settings.
The Identify method reads the HEIF image metadata, and the Decode methods convert the HEIF image data into an ImageSharp image format.
HeifDecoder Class:
This singleton class (Instance property) acts as a façade for the HeifDecoderCore class.
It exposes methods to identify and decode images, adapting them to the ImageSharp framework.
The Decode methods create an instance of HeifDecoderCore to perform the actual decoding work.
Helper Methods in HeifDecoderCore:
There are several helper methods to handle different chroma formats and bit depths, including managing alpha channels and byte-order considerations.
The FillImageMetadata method populates the image metadata from the HEIF image handle, such as EXIF and XMP profiles.
Important Security Advice:
Review and Understanding: Always review and understand the code you integrate into your projects, especially when it involves external libraries or handling complex file formats.
Dependency Management: Ensure that the libraries you use (LibHeifSharp, SixLabors.ImageSharp) are obtained from reputable sources and are up-to-date to avoid security vulnerabilities.
Runtime Environment: Run your applications in a secure and controlled environment, only granting necessary permissions to minimize potential risks.
Virus Concerns:
Source Verification: Ensure that any external libraries or binaries are downloaded from trusted and official repositories. For LibHeifSharp and SixLabors.ImageSharp, check their official GitHub repositories or package managers like NuGet.
Anti-Virus Software: Use robust and up-to-date anti-virus software to scan your machine and project files regularly.
In summary, the provided code has no apparent malicious content. It is focused on providing functionalities for HEIF image decoding. Exercise standard security practices when incorporating it into your projects to ensure a safe development environment. If you want to perform a security audit on the code libraries you depend on, consider using tools like static analyzers or security scanners specifically designed for software dependencies.