Editor/TextureChannels.cs
using System;
using System.IO;
using System.Threading;
using Sandbox;

namespace ImportUnityPackage;

public static class TextureChannels
{
	public static byte[] Extract( string source, int channel, double scale, bool invert, CancellationToken cancel )
	{
		using var bitmap = Bitmap.CreateFromBytes( File.ReadAllBytes( source ) );
		if ( bitmap == null ) throw new InvalidDataException( "Unable to decode packed texture: " + source );
		var pixels = bitmap.GetPixels();
		for ( var i = 0; i < pixels.Length; i++ )
		{
			if ( i % 65536 == 0 ) cancel.ThrowIfCancellationRequested();
			var p = pixels[i];
			var value = (float)Math.Clamp( (channel switch { 0 => p.r, 1 => p.g, 2 => p.b, _ => p.a }) * scale, 0, 1 );
			if ( invert ) value = 1 - value;
			pixels[i] = new Color( value, value, value, 1 );
		}
		bitmap.SetPixels( pixels );
		return bitmap.ToPng();
	}
}