wpf CroppedBitmap crop image as pixel values in double

随声附和 提交于 2020-01-03 05:10:09

问题


I am Cropping the image using CroppedBitmap method in WPF. Required input parameter is int32Rect. But, my image Height and Width values are in double (pixel). So without truncate the Double to Int, i want to crop the image by using double values (pixel)


回答1:


You need to use PixelWidth and PixelHeight properties, if you can't see them (Intellisense can't find them) you can use the as operator to cast it to a BitmapSource. For example:

BitmapSource src = yourImage as BitmapSource;
CroppedBitmap chunk = new CroppedBitmap(src, new Int32Rect(src.PixelWidth / 4, src.PixelHeight / 4, src.PixelWidth / 2, src.PixelHeight / 2));

By the way, the as operator returns null if conversion couldn't be performed (so you may want to check if src is not null after the conversion in the example above, unless you're sure that yourImage is derived from BitmapSource).


EDIT :

I'm not sure if this is what you need, but here is a method that accepts a Rect (floating-point values) as input and returns a CroppedBitmap:

    public static CroppedBitmap GetCroppedBitmap(BitmapSource src, Rect r)
    {
        double factorX, factorY;

        factorX = src.PixelWidth / src.Width;
        factorY = src.PixelHeight / src.Height;
        return new CroppedBitmap(src, new Int32Rect((int)Math.Round(r.X * factorX), (int)Math.Round(r.Y * factorY), (int)Math.Round(r.Width * factorX), (int)Math.Round(r.Height * factorY)));
    }

Example:

    BitmapImage bmp = new BitmapImage(new Uri(@"c:\Users\Public\Pictures\Sample Pictures\Koala.jpg", UriKind.Relative));
    CroppedBitmap chunk = GetCroppedBitmap(bmp, new Rect(bmp.Width / 4, bmp.Height / 4, bmp.Width / 2, bmp.Height / 2));
    JpegBitmapEncoder jpg = new JpegBitmapEncoder();
    jpg.Frames.Add(BitmapFrame.Create(chunk));
    FileStream fp = new FileStream("chunk.jpg", FileMode.Create, FileAccess.Write);
    jpg.Save(fp);
    fp.Close();


来源:https://stackoverflow.com/questions/14214827/wpf-croppedbitmap-crop-image-as-pixel-values-in-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!