wpf CroppedBitmap裁剪图像为double的像素值 [英] wpf CroppedBitmap crop image as pixel values in double

查看:757
本文介绍了wpf CroppedBitmap裁剪图像为double的像素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WPF中使用CroppedBitmap方法裁剪图像。
必需的输入参数是int32Rect。
但是,我的图像高度和宽度值是双(像素)。
因此,如果不截断Double to Int,我想通过使用双值(像素)裁剪图像

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)

推荐答案

您需要使用 PixelWidth PixelHeight 属性,如果您看不到它们( Intellisense 找不到它们),您可以使用 as 运算符将其强制转换为 BitmapSource 。例如:

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));

顺便说一句, as 运算符返回 null 如果无法执行转换(因此您可能需要在转换后检查 src 是否 null 在上面的示例中,除非您确定 yourImage 派生自 BitmapSource )。



编辑:

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 :

我不确定这是否是你需要的,但这里是一种接受 Rect (浮点值)作为输入并返回 CroppedBitmap 的方法:

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)));
    }

示例:

    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();

这篇关于wpf CroppedBitmap裁剪图像为double的像素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆