Browse Source

Merge pull request #720 from carbon/png

Improve PNG CQ2
af/merge-core
James Jackson-South 7 years ago
committed by GitHub
parent
commit
680ff876a3
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 34
      src/ImageSharp/Common/Extensions/EncoderExtensions.cs
  2. 107
      src/ImageSharp/Formats/Png/Chunks/PhysicalChunkData.cs
  3. 12
      src/ImageSharp/Formats/Png/PngConstants.cs
  4. 164
      src/ImageSharp/Formats/Png/PngDecoderCore.cs
  5. 44
      src/ImageSharp/Formats/Png/PngEncoderCore.cs
  6. 30
      src/ImageSharp/Formats/Png/PngHeader.cs
  7. 13
      src/ImageSharp/MetaData/Profiles/Exif/ExifReader.cs

34
src/ImageSharp/Common/Extensions/EncoderExtensions.cs

@ -0,0 +1,34 @@
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
#if !NETCOREAPP2_1
using System;
using System.Text;
namespace SixLabors.ImageSharp
{
/// <summary>
/// Extension methods for the <see cref="Encoder"/> type.
/// </summary>
internal static unsafe class EncoderExtensions
{
/// <summary>
/// Gets a string from the provided buffer data.
/// </summary>
/// <param name="encoding">The encoding.</param>
/// <param name="buffer">The buffer.</param>
/// <returns>The string.</returns>
public static string GetString(this Encoding encoding, ReadOnlySpan<byte> buffer)
{
#if NETSTANDARD1_1
return encoding.GetString(buffer.ToArray());
#else
fixed (byte* bytes = buffer)
{
return encoding.GetString(bytes, buffer.Length);
}
#endif
}
}
}
#endif

107
src/ImageSharp/Formats/Png/Chunks/PhysicalChunkData.cs

@ -0,0 +1,107 @@
using System;
using System.Buffers.Binary;
using SixLabors.ImageSharp.Common.Helpers;
using SixLabors.ImageSharp.MetaData;
namespace SixLabors.ImageSharp.Formats.Png.Chunks
{
/// <summary>
/// The pHYs chunk specifies the intended pixel size or aspect ratio for display of the image.
/// </summary>
internal readonly struct PhysicalChunkData
{
public const int Size = 9;
public PhysicalChunkData(uint x, uint y, byte unitSpecifier)
{
this.XAxisPixelsPerUnit = x;
this.YAxisPixelsPerUnit = y;
this.UnitSpecifier = unitSpecifier;
}
/// <summary>
/// Gets the number of pixels per unit on the X axis.
/// </summary>
public uint XAxisPixelsPerUnit { get; }
/// <summary>
/// Gets the number of pixels per unit on the Y axis.
/// </summary>
public uint YAxisPixelsPerUnit { get; }
/// <summary>
/// Gets the unit specifier.
/// 0: unit is unknown
/// 1: unit is the meter
/// When the unit specifier is 0, the pHYs chunk defines pixel aspect ratio only; the actual size of the pixels remains unspecified.
/// </summary>
public byte UnitSpecifier { get; }
/// <summary>
/// Parses the PhysicalChunkData from the given buffer.
/// </summary>
/// <param name="data">The data buffer.</param>
/// <returns>The parsed PhysicalChunkData.</returns>
public static PhysicalChunkData Parse(ReadOnlySpan<byte> data)
{
uint hResolution = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(0, 4));
uint vResolution = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(4, 4));
byte unit = data[8];
return new PhysicalChunkData(hResolution, vResolution, unit);
}
/// <summary>
/// Constructs the PngPhysicalChunkData from the provided metadata.
/// If the resolution units are not in meters, they are automatically convereted.
/// </summary>
/// <param name="meta">The metadata.</param>
/// <returns>The constructed PngPhysicalChunkData instance.</returns>
public static PhysicalChunkData FromMetadata(ImageMetaData meta)
{
byte unitSpecifier = 0;
uint x;
uint y;
switch (meta.ResolutionUnits)
{
case PixelResolutionUnit.AspectRatio:
unitSpecifier = 0; // Unspecified
x = (uint)Math.Round(meta.HorizontalResolution);
y = (uint)Math.Round(meta.VerticalResolution);
break;
case PixelResolutionUnit.PixelsPerInch:
unitSpecifier = 1; // Per meter
x = (uint)Math.Round(UnitConverter.InchToMeter(meta.HorizontalResolution));
y = (uint)Math.Round(UnitConverter.InchToMeter(meta.VerticalResolution));
break;
case PixelResolutionUnit.PixelsPerCentimeter:
unitSpecifier = 1; // Per meter
x = (uint)Math.Round(UnitConverter.CmToMeter(meta.HorizontalResolution));
y = (uint)Math.Round(UnitConverter.CmToMeter(meta.VerticalResolution));
break;
default:
unitSpecifier = 1; // Per meter
x = (uint)Math.Round(meta.HorizontalResolution);
y = (uint)Math.Round(meta.VerticalResolution);
break;
}
return new PhysicalChunkData(x, y, unitSpecifier);
}
/// <summary>
/// Writes the data to the given buffer.
/// </summary>
/// <param name="buffer">The buffer.</param>
public void WriteTo(Span<byte> buffer)
{
BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(0, 4), this.XAxisPixelsPerUnit);
BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(4, 4), this.YAxisPixelsPerUnit);
buffer[8] = this.UnitSpecifier;
}
}
}

12
src/ImageSharp/Formats/Png/PngConstants.cs

@ -41,5 +41,17 @@ namespace SixLabors.ImageSharp.Formats.Png
/// The header bytes as a big endian coded ulong.
/// </summary>
public const ulong HeaderValue = 0x89504E470D0A1A0AUL;
/// <summary>
/// The dictionary of available color types.
/// </summary>
public static readonly Dictionary<PngColorType, byte[]> ColorTypes = new Dictionary<PngColorType, byte[]>()
{
[PngColorType.Grayscale] = new byte[] { 1, 2, 4, 8, 16 },
[PngColorType.Rgb] = new byte[] { 8, 16 },
[PngColorType.Palette] = new byte[] { 1, 2, 4, 8 },
[PngColorType.GrayscaleWithAlpha] = new byte[] { 8, 16 },
[PngColorType.RgbWithAlpha] = new byte[] { 8, 16 }
};
}
}

164
src/ImageSharp/Formats/Png/PngDecoderCore.cs

@ -3,13 +3,12 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.Formats.Png.Chunks;
using SixLabors.ImageSharp.Formats.Png.Filters;
using SixLabors.ImageSharp.Formats.Png.Zlib;
using SixLabors.ImageSharp.Memory;
@ -26,31 +25,9 @@ namespace SixLabors.ImageSharp.Formats.Png
internal sealed class PngDecoderCore
{
/// <summary>
/// The dictionary of available color types.
/// Reusable buffer.
/// </summary>
private static readonly Dictionary<PngColorType, byte[]> ColorTypes = new Dictionary<PngColorType, byte[]>()
{
[PngColorType.Grayscale] = new byte[] { 1, 2, 4, 8, 16 },
[PngColorType.Rgb] = new byte[] { 8, 16 },
[PngColorType.Palette] = new byte[] { 1, 2, 4, 8 },
[PngColorType.GrayscaleWithAlpha] = new byte[] { 8, 16 },
[PngColorType.RgbWithAlpha] = new byte[] { 8, 16 }
};
/// <summary>
/// Reusable buffer for reading chunk types.
/// </summary>
private readonly byte[] chunkTypeBuffer = new byte[4];
/// <summary>
/// Reusable buffer for reading chunk lengths.
/// </summary>
private readonly byte[] chunkLengthBuffer = new byte[4];
/// <summary>
/// Reusable buffer for reading crc values.
/// </summary>
private readonly byte[] crcBuffer = new byte[4];
private readonly byte[] buffer = new byte[4];
/// <summary>
/// Reusable crc for validating chunks.
@ -220,7 +197,6 @@ namespace SixLabors.ImageSharp.Formats.Png
{
case PngChunkType.Header:
this.ReadHeaderChunk(pngMetaData, chunk.Data.Array);
this.ValidateHeader();
break;
case PngChunkType.Physical:
this.ReadPhysicalChunk(metaData, chunk.Data.GetSpan());
@ -253,7 +229,7 @@ namespace SixLabors.ImageSharp.Formats.Png
this.AssignTransparentMarkers(alpha);
break;
case PngChunkType.Text:
this.ReadTextChunk(metaData, chunk.Data.Array, chunk.Length);
this.ReadTextChunk(metaData, chunk.Data.Array.AsSpan(0, chunk.Length));
break;
case PngChunkType.Exif:
if (!this.ignoreMetadata)
@ -309,7 +285,6 @@ namespace SixLabors.ImageSharp.Formats.Png
{
case PngChunkType.Header:
this.ReadHeaderChunk(pngMetaData, chunk.Data.Array);
this.ValidateHeader();
break;
case PngChunkType.Physical:
this.ReadPhysicalChunk(metaData, chunk.Data.GetSpan());
@ -321,7 +296,7 @@ namespace SixLabors.ImageSharp.Formats.Png
this.SkipChunkDataAndCrc(chunk);
break;
case PngChunkType.Text:
this.ReadTextChunk(metaData, chunk.Data.Array, chunk.Length);
this.ReadTextChunk(metaData, chunk.Data.Array.AsSpan(0, chunk.Length));
break;
case PngChunkType.End:
this.isEndChunkReached = true;
@ -402,26 +377,14 @@ namespace SixLabors.ImageSharp.Formats.Png
/// <param name="data">The data containing physical data.</param>
private void ReadPhysicalChunk(ImageMetaData metadata, ReadOnlySpan<byte> data)
{
// The pHYs chunk specifies the intended pixel size or aspect ratio for display of the image. It contains:
// Pixels per unit, X axis: 4 bytes (unsigned integer)
// Pixels per unit, Y axis: 4 bytes (unsigned integer)
// Unit specifier: 1 byte
//
// The following values are legal for the unit specifier:
// 0: unit is unknown
// 1: unit is the meter
//
// When the unit specifier is 0, the pHYs chunk defines pixel aspect ratio only; the actual size of the pixels remains unspecified.
int hResolution = BinaryPrimitives.ReadInt32BigEndian(data.Slice(0, 4));
int vResolution = BinaryPrimitives.ReadInt32BigEndian(data.Slice(4, 4));
byte unit = data[8];
metadata.ResolutionUnits = unit == byte.MinValue
var physicalChunk = PhysicalChunkData.Parse(data);
metadata.ResolutionUnits = physicalChunk.UnitSpecifier == byte.MinValue
? PixelResolutionUnit.AspectRatio
: PixelResolutionUnit.PixelsPerMeter;
metadata.HorizontalResolution = hResolution;
metadata.VerticalResolution = vResolution;
metadata.HorizontalResolution = physicalChunk.XAxisPixelsPerUnit;
metadata.VerticalResolution = physicalChunk.YAxisPixelsPerUnit;
}
/// <summary>
@ -573,22 +536,18 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case FilterType.Sub:
SubFilter.Decode(scanlineSpan, this.bytesPerPixel);
break;
case FilterType.Up:
UpFilter.Decode(scanlineSpan, this.previousScanline.GetSpan());
break;
case FilterType.Average:
AverageFilter.Decode(scanlineSpan, this.previousScanline.GetSpan(), this.bytesPerPixel);
break;
case FilterType.Paeth:
PaethFilter.Decode(scanlineSpan, this.previousScanline.GetSpan(), this.bytesPerPixel);
break;
@ -647,22 +606,18 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case FilterType.Sub:
SubFilter.Decode(scanSpan, this.bytesPerPixel);
break;
case FilterType.Up:
UpFilter.Decode(scanSpan, prevSpan);
break;
case FilterType.Average:
AverageFilter.Decode(scanSpan, prevSpan, this.bytesPerPixel);
break;
case FilterType.Paeth:
PaethFilter.Decode(scanSpan, prevSpan, this.bytesPerPixel);
break;
@ -715,7 +670,6 @@ namespace SixLabors.ImageSharp.Formats.Png
switch (this.pngColorType)
{
case PngColorType.Grayscale:
PngScanlineProcessor.ProcessGrayscaleScanline(
this.header,
scanlineSpan,
@ -727,7 +681,6 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case PngColorType.GrayscaleWithAlpha:
PngScanlineProcessor.ProcessGrayscaleWithAlphaScanline(
this.header,
scanlineSpan,
@ -738,7 +691,6 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case PngColorType.Palette:
PngScanlineProcessor.ProcessPaletteScanline(
this.header,
scanlineSpan,
@ -749,7 +701,6 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case PngColorType.Rgb:
PngScanlineProcessor.ProcessRgbScanline(
this.header,
scanlineSpan,
@ -763,7 +714,6 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case PngColorType.RgbWithAlpha:
PngScanlineProcessor.ProcessRgbaScanline(
this.header,
scanlineSpan,
@ -799,7 +749,6 @@ namespace SixLabors.ImageSharp.Formats.Png
switch (this.pngColorType)
{
case PngColorType.Grayscale:
PngScanlineProcessor.ProcessInterlacedGrayscaleScanline(
this.header,
scanlineSpan,
@ -813,7 +762,6 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case PngColorType.GrayscaleWithAlpha:
PngScanlineProcessor.ProcessInterlacedGrayscaleWithAlphaScanline(
this.header,
scanlineSpan,
@ -826,7 +774,6 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case PngColorType.Palette:
PngScanlineProcessor.ProcessInterlacedPaletteScanline(
this.header,
scanlineSpan,
@ -839,7 +786,6 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case PngColorType.Rgb:
PngScanlineProcessor.ProcessInterlacedRgbScanline(
this.header,
scanlineSpan,
@ -855,7 +801,6 @@ namespace SixLabors.ImageSharp.Formats.Png
break;
case PngColorType.RgbWithAlpha:
PngScanlineProcessor.ProcessInterlacedRgbaScanline(
this.header,
scanlineSpan,
@ -886,6 +831,7 @@ namespace SixLabors.ImageSharp.Formats.Png
ushort rc = BinaryPrimitives.ReadUInt16LittleEndian(alpha.Slice(0, 2));
ushort gc = BinaryPrimitives.ReadUInt16LittleEndian(alpha.Slice(2, 2));
ushort bc = BinaryPrimitives.ReadUInt16LittleEndian(alpha.Slice(4, 2));
this.rgb48Trans = new Rgb48(rc, gc, bc);
this.hasTrans = true;
return;
@ -925,37 +871,10 @@ namespace SixLabors.ImageSharp.Formats.Png
{
this.header = PngHeader.Parse(data);
this.header.Validate();
pngMetaData.BitDepth = (PngBitDepth)this.header.BitDepth;
pngMetaData.ColorType = this.header.ColorType;
}
/// <summary>
/// Validates the png header.
/// </summary>
/// <exception cref="NotSupportedException">
/// Thrown if the image does pass validation.
/// </exception>
private void ValidateHeader()
{
if (!ColorTypes.ContainsKey(this.header.ColorType))
{
throw new NotSupportedException("Color type is not supported or not valid.");
}
if (!ColorTypes[this.header.ColorType].Contains(this.header.BitDepth))
{
throw new NotSupportedException("Bit depth is not supported or not valid.");
}
if (this.header.FilterMethod != 0)
{
throw new NotSupportedException("The png specification only defines 0 as filter method.");
}
if (this.header.InterlaceMethod != PngInterlaceMode.None && this.header.InterlaceMethod != PngInterlaceMode.Adam7)
{
throw new NotSupportedException("The png specification only defines 'None' and 'Adam7' as interlaced methods.");
}
this.pngColorType = this.header.ColorType;
}
@ -964,28 +883,18 @@ namespace SixLabors.ImageSharp.Formats.Png
/// Reads a text chunk containing image properties from the data.
/// </summary>
/// <param name="metadata">The metadata to decode to.</param>
/// <param name="data">The <see cref="T:byte[]"/> containing data.</param>
/// <param name="length">The maximum length to read.</param>
private void ReadTextChunk(ImageMetaData metadata, byte[] data, int length)
/// <param name="data">The <see cref="T:Span"/> containing the data.</param>
private void ReadTextChunk(ImageMetaData metadata, ReadOnlySpan<byte> data)
{
if (this.ignoreMetadata)
{
return;
}
int zeroIndex = 0;
for (int i = 0; i < length; i++)
{
if (data[i] == 0)
{
zeroIndex = i;
break;
}
}
int zeroIndex = data.IndexOf((byte)0);
string name = this.textEncoding.GetString(data, 0, zeroIndex);
string value = this.textEncoding.GetString(data, zeroIndex + 1, length - zeroIndex - 1);
string name = this.textEncoding.GetString(data.Slice(0, zeroIndex));
string value = this.textEncoding.GetString(data.Slice(zeroIndex + 1));
metadata.Properties.Add(new ImageProperty(name, value));
}
@ -1001,7 +910,7 @@ namespace SixLabors.ImageSharp.Formats.Png
return 0;
}
this.currentStream.Read(this.crcBuffer, 0, 4);
this.currentStream.Read(this.buffer, 0, 4);
if (this.TryReadChunk(out PngChunk chunk))
{
@ -1086,13 +995,17 @@ namespace SixLabors.ImageSharp.Formats.Png
/// <param name="chunk">The <see cref="PngChunk"/>.</param>
private void ValidateChunk(in PngChunk chunk)
{
Span<byte> chunkType = stackalloc byte[4];
BinaryPrimitives.WriteUInt32BigEndian(chunkType, (uint)chunk.Type);
this.crc.Reset();
this.crc.Update(this.chunkTypeBuffer);
this.crc.Update(chunkType);
this.crc.Update(chunk.Data.GetSpan());
if (this.crc.Value != chunk.Crc)
{
string chunkTypeName = Encoding.UTF8.GetString(this.chunkTypeBuffer, 0, 4);
string chunkTypeName = Encoding.UTF8.GetString(chunkType);
throw new ImageFormatException($"CRC Error. PNG {chunkTypeName} chunk is corrupt!");
}
@ -1106,14 +1019,9 @@ namespace SixLabors.ImageSharp.Formats.Png
/// </exception>
private uint ReadChunkCrc()
{
int numBytes = this.currentStream.Read(this.crcBuffer, 0, 4);
if (numBytes >= 1 && numBytes <= 3)
{
throw new ImageFormatException("Image stream is not valid!");
}
return BinaryPrimitives.ReadUInt32BigEndian(this.crcBuffer);
return this.currentStream.Read(this.buffer, 0, 4) == 4
? BinaryPrimitives.ReadUInt32BigEndian(this.buffer)
: throw new ImageFormatException("Image stream is not valid!");
}
/// <summary>
@ -1148,22 +1056,22 @@ namespace SixLabors.ImageSharp.Formats.Png
/// </exception>
private PngChunkType ReadChunkType()
{
return this.currentStream.Read(this.chunkTypeBuffer, 0, 4) == 4
? (PngChunkType)BinaryPrimitives.ReadUInt32BigEndian(this.chunkTypeBuffer.AsSpan())
return this.currentStream.Read(this.buffer, 0, 4) == 4
? (PngChunkType)BinaryPrimitives.ReadUInt32BigEndian(this.buffer)
: throw new ImageFormatException("Invalid PNG data.");
}
/// <summary>
/// Calculates the length of the given chunk.
/// Attempts to read the length of the next chunk.
/// </summary>
/// <exception cref="ImageFormatException">
/// Thrown if the input stream is not valid.
/// </exception>
/// <returns>
/// Whether the the length was read.
/// </returns>
private bool TryReadChunkLength(out int result)
{
if (this.currentStream.Read(this.chunkLengthBuffer, 0, 4) == 4)
if (this.currentStream.Read(this.buffer, 0, 4) == 4)
{
result = BinaryPrimitives.ReadInt32BigEndian(this.chunkLengthBuffer);
result = BinaryPrimitives.ReadInt32BigEndian(this.buffer);
return true;
}

44
src/ImageSharp/Formats/Png/PngEncoderCore.cs

@ -9,7 +9,7 @@ using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.Common.Helpers;
using SixLabors.ImageSharp.Formats.Png.Chunks;
using SixLabors.ImageSharp.Formats.Png.Filters;
using SixLabors.ImageSharp.Formats.Png.Zlib;
using SixLabors.ImageSharp.Memory;
@ -674,47 +674,9 @@ namespace SixLabors.ImageSharp.Formats.Png
/// <param name="meta">The image meta data.</param>
private void WritePhysicalChunk(Stream stream, ImageMetaData meta)
{
// The pHYs chunk specifies the intended pixel size or aspect ratio for display of the image. It contains:
// Pixels per unit, X axis: 4 bytes (unsigned integer)
// Pixels per unit, Y axis: 4 bytes (unsigned integer)
// Unit specifier: 1 byte
//
// The following values are legal for the unit specifier:
// 0: unit is unknown
// 1: unit is the meter
//
// When the unit specifier is 0, the pHYs chunk defines pixel aspect ratio only; the actual size of the pixels remains unspecified.
Span<byte> hResolution = this.chunkDataBuffer.AsSpan(0, 4);
Span<byte> vResolution = this.chunkDataBuffer.AsSpan(4, 4);
switch (meta.ResolutionUnits)
{
case PixelResolutionUnit.AspectRatio:
this.chunkDataBuffer[8] = 0;
BinaryPrimitives.WriteInt32BigEndian(hResolution, (int)Math.Round(meta.HorizontalResolution));
BinaryPrimitives.WriteInt32BigEndian(vResolution, (int)Math.Round(meta.VerticalResolution));
break;
case PixelResolutionUnit.PixelsPerInch:
this.chunkDataBuffer[8] = 1; // Per meter
BinaryPrimitives.WriteInt32BigEndian(hResolution, (int)Math.Round(UnitConverter.InchToMeter(meta.HorizontalResolution)));
BinaryPrimitives.WriteInt32BigEndian(vResolution, (int)Math.Round(UnitConverter.InchToMeter(meta.VerticalResolution)));
break;
case PixelResolutionUnit.PixelsPerCentimeter:
this.chunkDataBuffer[8] = 1; // Per meter
BinaryPrimitives.WriteInt32BigEndian(hResolution, (int)Math.Round(UnitConverter.CmToMeter(meta.HorizontalResolution)));
BinaryPrimitives.WriteInt32BigEndian(vResolution, (int)Math.Round(UnitConverter.CmToMeter(meta.VerticalResolution)));
break;
default:
this.chunkDataBuffer[8] = 1; // Per meter
BinaryPrimitives.WriteInt32BigEndian(hResolution, (int)Math.Round(meta.HorizontalResolution));
BinaryPrimitives.WriteInt32BigEndian(vResolution, (int)Math.Round(meta.VerticalResolution));
break;
}
PhysicalChunkData.FromMetadata(meta).WriteTo(this.chunkDataBuffer);
this.WriteChunk(stream, PngChunkType.Physical, this.chunkDataBuffer, 0, 9);
this.WriteChunk(stream, PngChunkType.Physical, this.chunkDataBuffer, 0, PhysicalChunkData.Size);
}
/// <summary>

30
src/ImageSharp/Formats/Png/PngHeader.cs

@ -80,6 +80,36 @@ namespace SixLabors.ImageSharp.Formats.Png
/// </summary>
public PngInterlaceMode InterlaceMethod { get; }
/// <summary>
/// Validates the png header.
/// </summary>
/// <exception cref="NotSupportedException">
/// Thrown if the image does pass validation.
/// </exception>
public void Validate()
{
if (!PngConstants.ColorTypes.TryGetValue(this.ColorType, out byte[] supportedBitDepths))
{
throw new NotSupportedException($"Invalid or unsupported color type. Was '{this.ColorType}'.");
}
if (supportedBitDepths.AsSpan().IndexOf(this.BitDepth) == -1)
{
throw new NotSupportedException($"Invalid or unsupported bit depth. Was '{this.BitDepth}'.");
}
if (this.FilterMethod != 0)
{
throw new NotSupportedException($"Invalid filter method. Expected 0. Was '{this.FilterMethod}'.");
}
// The png specification only defines 'None' and 'Adam7' as interlaced methods.
if (this.InterlaceMethod != PngInterlaceMode.None && this.InterlaceMethod != PngInterlaceMode.Adam7)
{
throw new NotSupportedException($"Invalid interlace method. Expected 'None' or 'Adam7'. Was '{this.InterlaceMethod}'.");
}
}
/// <summary>
/// Writes the header to the given buffer.
/// </summary>

13
src/ImageSharp/MetaData/Profiles/Exif/ExifReader.cs

@ -127,25 +127,14 @@ namespace SixLabors.ImageSharp.MetaData.Profiles.Exif
private unsafe string ConvertToString(ReadOnlySpan<byte> buffer)
{
Span<byte> nullChar = stackalloc byte[1] { 0 };
int nullCharIndex = buffer.IndexOf(nullChar);
int nullCharIndex = buffer.IndexOf((byte)0);
if (nullCharIndex > -1)
{
buffer = buffer.Slice(0, nullCharIndex);
}
#if NETSTANDARD1_1
return Encoding.UTF8.GetString(buffer.ToArray(), 0, buffer.Length);
#elif NETCOREAPP2_1
return Encoding.UTF8.GetString(buffer);
#else
fixed (byte* pointer = &MemoryMarshal.GetReference(buffer))
{
return Encoding.UTF8.GetString(pointer, buffer.Length);
}
#endif
}
/// <summary>

Loading…
Cancel
Save