Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 裁剪位图并根据需要扩展大小_C#_Image Processing - Fatal编程技术网

C# 裁剪位图并根据需要扩展大小

C# 裁剪位图并根据需要扩展大小,c#,image-processing,C#,Image Processing,我想用这个函数裁剪位图,但是位图可能比裁剪区域小,所以在这种情况下我想让位图变大 例如,我有一个200x250的位图,如果我对250x250使用CropBitmap方法,我会得到一个内存不足错误。它应该返回一个250x250的位图,其中缺少的左50px用白色填充 我怎样才能做到这一点 public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight) { var rect

我想用这个函数裁剪位图,但是位图可能比裁剪区域小,所以在这种情况下我想让位图变大

例如,我有一个200x250的位图,如果我对250x250使用CropBitmap方法,我会得到一个内存不足错误。它应该返回一个250x250的位图,其中缺少的左50px用白色填充

我怎样才能做到这一点

public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
{
    var rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);

    if(bitmap.Width < cropWidth || bitmap.Height < cropHeight)
    {
        // what now?
    }

    return bitmap.Clone(rect, bitmap.PixelFormat);
}
公共位图CropBitmap(位图、int-cropX、int-cropY、int-cropWidth、int-cropHeight)
{
var rect=新矩形(cropX、cropY、cropWidth、cropHeight);
if(bitmap.Width
创建具有适当大小的新位图。然后获取一个
System.Drawing.Graphics
并使用它创建白色区域并插入源图像。大概是这样的:

    if (bitmap.Width < cropWidth && bitmap.Height < cropHeight)
    {
        Bitmap newImage = new Bitmap(cropWidth, cropHeight, bitmap.PixelFormat);
        using (Graphics g = Graphics.FromImage(newImage))
        {
            // fill target image with white color
            g.FillRectangle(Brushes.White, 0, 0, cropWidth, cropHeight);

            // place source image inside the target image
            var dstX = cropWidth - bitmap.Width;
            var dstY = cropHeight - bitmap.Height;
            g.DrawImage(bitmap, dstX, dstY);
        }
        return newImage;
    }
if(bitmap.Width

注意,我将外部
if
表达式中的
|
替换为
&
。要使其与
|
一起工作,您必须计算源区域并使用

这可能有助于您调整大小:我必须将
dstX=cropWidth-bitmap.Width
切换到
dstX=bitmap.Width-cropWidth
,但这很有效-谢谢!(与dstY相同)