Forum Libraries, Components, and Plugins

Surface.Snapshot.Encode jpeg much worse than png after many iterations

I have a game where I basically encode parts (rectangles) of a larger image over and over, saving the results in a be read back and repeated over and over. This may occur thousands of times. I don't do any manipulation of the starting image...just copy small rectangles around. After each iteration, I get the bytes from the surface to save in a database.

bytes = surface.Snapshot().Encode(SKEncodedImageFormat.Jpeg, 100).ToArray();

I've noticed that even after maybe 10 iterations of loading, copying, encoding, saving, the jpeg result begins to lose some clarity and definitely a lose of color vibrance. I am using a 100% quality.

If I change the encoding to SKEncodedImageFormat.Png, the end result is great...just like the original image. Unfortunately, the png encoding takes significantly longer and the resulting file size is 3 times the size of the jpeg.

It seems to be the result of the surface Encode method. Any ideas how I can get a better encoding quality with Jpeg?

Maybe there is some way using SkiaSharp that I'm not aware of to copy a rectangle from a source set of bytes to another set of bytes without having to encode the surface.



  • mattleibowmattleibow ZAXamarin Team Xamurai

    You can probably do what you want using the resulting SKImage from surface.Snapshot().

    var snap = surface.Snapshot();

    If you don't want to copy the pixels, can can wrap the pixels:

    var snap = SKImage.FromPixels(surface.PeekPixels());

    You can then take the subset that you want:

    var subset = snap.Subset(SKRectI.Create(10, 10, 100, 100));

    You can either encode the smaller bitmap as a .PNG using Encode(), or you can just save the raw bytes:

    var pix = subset.PeekPixels();
    var data = SKData.Create(pix.GetPixels(), pix.Info.BytesSize);
    var bytes = data.ToArray();

    Remember, the raw pixels have no attributes, so you will have to also save the width, height, color type, and alpha type. I would suggest the .PNG, unless you prefer speed (save raw bytes) over size (encode .PNG).

  • mattleibowmattleibow ZAXamarin Team Xamurai
Sign In or Register to comment.