Skip to content

Instantly share code, notes, and snippets.

@nuitsjp
Created October 17, 2016 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuitsjp/9838b762f5c464e7ea05de0b0a352648 to your computer and use it in GitHub Desktop.
Save nuitsjp/9838b762f5c464e7ea05de0b0a352648 to your computer and use it in GitHub Desktop.
BitmapSource to expand while maintaining the DPI.
public static BitmapSource Resize(this BitmapSource source, int resolution)
{
var scale = resolution / source.DpiX;
// サイズ変更
var transformedBitmap = new TransformedBitmap();
transformedBitmap.BeginInit();
transformedBitmap.Source = source;
transformedBitmap.Transform = new ScaleTransform(scale, scale);
transformedBitmap.EndInit();
// 一旦バイト列へ変換し
int stride = transformedBitmap.PixelWidth * (transformedBitmap.Format.BitsPerPixel + 7) / 8;
byte[] data = new byte[stride * transformedBitmap.PixelHeight];
transformedBitmap.CopyPixels(data, stride, 0);
// DPIを指定サイズに変更したイメージにコピーする
WriteableBitmap target = new WriteableBitmap(
transformedBitmap.PixelWidth,
transformedBitmap.PixelHeight,
resolution, resolution,
transformedBitmap.Format, null);
target.WritePixels(
new Int32Rect(0, 0, transformedBitmap.PixelWidth, transformedBitmap.PixelHeight),
data, stride, 0);
target.Freeze();
return target;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment