سؤال

I have a puzzle game and I can create levels. When I save a level, it takes a snapshot of the canvas and then when I choose a level, it displays all the pictures of the levels next to their name as a thumbnail. However each image is around 1MB in size. I would like to get them to around 30KB in size. Also the file it makes cannot be edited by a photo editor to make it a smaller size even though it is a jpg. I see I have used a TiffBitmapEncoder whoops. Probably my issue with the photo editors.

Here is my code:

private void saveImage(object sender, EventArgs e)
{
    string path = myImageNamePath;
    FileStream fs = new FileStream(path, FileMode.Create);
    RenderTargetBitmap bmp = new RenderTargetBitmap((int)myLevelDesigner.pbxMap.ActualWidth,
        (int)myLevelDesigner.pbxMap.ActualHeight, 1 / 96, 1 / 96, PixelFormats.Pbgra32);
    bmp.Render(myLevelDesigner.pbxMap);
    BitmapEncoder encoder = new TiffBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bmp));
    encoder.Save(fs);
    fs.Close();
}
هل كانت مفيدة؟

المحلول

Oh my, is there a particular reason you are using the TIFF file format? I highly recommend using PNG instead, it is lossless and compressed.

Use PngBitmapEncoder instead, most graphics programs support PNG.

I would also recommend making it into an extension method that you can reuse throughout. Something like this:

public static class CanvasExtender
{
  public static void SaveToImageFile(this Canvas canvas, string outputFile)
  {
    canvas.UpdateLayout();

    var bitmap = new RenderTargetBitmap(canvas.ActualWidth, canvas.ActualHeight, 96d, 96d, PixelFormats.Pbgra32);
    bitmap.Render(canvas);

    var encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmap));

    using(var outputStream = File.Create(outputFile))
      encoder.Save(outputStream);
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top