Skip to content

Instantly share code, notes, and snippets.

@nuitsjp
Created October 17, 2016 02:15
Embed
What would you like to do?
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