docnet
docnet copied to clipboard
Are there any examples that uses SkiaSharp to save and manipulate the PDF image?
I tried to search an example that uses SkiaSharp to manipulate images instead of System.Drawings because i am using linux.
public static (byte[] content, int width, int height) ToImage(this byte[] fileBytes, int page = 0)
{
var docReader = DocLib.Instance.GetDocReader(fileBytes,DefaultPageDimensions);
var pageReader = docReader.GetPageReader(page);
var image = pageReader.GetImage();
if (image == null)
{
throw new Exception("Could not find image in PDF");
}
var width = pageReader.GetPageWidth();
var height = pageReader.GetPageHeight();
return (image, width, height);
}
public static SKBitmap ToSkiaImage(this byte[] fileBytes, int page = 0)
{
var (imageContent, width, height) = fileBytes.ToImage(page);
var bitmap = new SKBitmap(width, height);
var array = new byte[bitmap.RowBytes * bitmap.Height];
for (var i = 0; i < imageContent.Length; i++)
{
var color = new SKColor(imageContent[i]);
var num = i % width;
var num2 = i / width;
array[bitmap.RowBytes * num2 + 4 * num] = color.Blue;
array[bitmap.RowBytes * num2 + 4 * num + 1] = color.Green;
array[bitmap.RowBytes * num2 + 4 * num + 2] = color.Red;
array[bitmap.RowBytes * num2 + 4 * num + 3] = color.Alpha;
}
var pixels = bitmap.GetPixels();
Marshal.Copy(array, 0, pixels, array.Length);
return bitmap;
}
This is as far as i got.
public static SKBitmap ToSkiaImage(this byte[] fileBytes, int page = 0)
{
var (imageContent, width, height) = fileBytes.ToImage(page);
var memoryStream = new MemoryStream(imageContent);
var skData = SKData.Create(memoryStream);
var bitmap = SKBitmap.Decode(skData, new SKImageInfo(width, height, SKColorType.Bgra8888));
return bitmap;
}
I tried with this method as well, and the bitmap return null
Not far from my working solution
public static SKBitmap ToSkiaImage(byte[] bytes, int width, int height)
{
var bmp = new SKBitmap(new SKImageInfo(width, height,SKColorType.Bgra8888));
Marshal.Copy(bytes, 0, bmp.GetPixels(), bytes.Length);
return bmp;
}
Triaged and approved, will add an example