Created
October 17, 2016 02:15
-
-
Save nuitsjp/9838b762f5c464e7ea05de0b0a352648 to your computer and use it in GitHub Desktop.
BitmapSource to expand while maintaining the DPI.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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