Powershell 在 System.Drawing 中使用 .NET .DrawImage

2024-02-23

我正在制作一个工具,可以自动裁剪和定位,无需将图像大小调整为其他图像。 我发现this https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.drawimageunscaled?view=netframework-4.7.2在 .NET 的微软文档上,但我无法理解如何在我的代码中实现。到目前为止,我可以从 Mojang API 下载图像,例如:

Bernd_L.png
Bernd_L.png

Steve.png
Steve

I was wondering if I could crop a rectangle of 8x8 pixel at coordinates of 8,0 1.png and paste it on top of Steve.png at coordinates 8,8 so at the end the output will look like this:

output.png
output.png

我应该如何使用.NET函数.DrawImage实现高收成?

EDIT

感谢@Caramiriel 提供的链接,我终于可以使用此脚本裁剪图像的区域:

Add-Type -AssemblyName System.Drawing

$Username = "Steve"

$destRect = new-object Drawing.Rectangle 8, 0, 8, 8
$srcRect = new-object Drawing.Rectangle 0, 8, 8, 8
$src=[System.Drawing.Image]::FromFile("$pwd\$Username.png")
$bmp=new-object System.Drawing.Bitmap 64,64
$graphics=[System.Drawing.Graphics]::FromImage($bmp)
$units = [System.Drawing.GraphicsUnit]::Pixel
$graphics.DrawImage($src, $destRect, $srcRect, $units)
$graphics.Dispose()
$bmp.Save("$pwd\output.png")

如果有一种更紧凑/优雅的方法来做到这一点,我真的很想知道!

EDIT 2

我发布了一个带有通用功能的答案来完成这项工作。


正如建议的@马蒂亚斯·R·杰森 https://stackoverflow.com/users/712649/mathias-r-jessen我使用了一个函数,所以它看起来更优雅:

Add-Type -AssemblyName System.Drawing

$Username="Steve"

$bmp=new-object System.Drawing.Bitmap 64,64
$graphics=[System.Drawing.Graphics]::FromImage($bmp)
$src=[System.Drawing.Image]::FromFile("$pwd\$Username.png")
$units = [System.Drawing.GraphicsUnit]::Pixel

function DrawCroppedImage {
    param( [int]$srcX, [int]$srcY, [int]$srcWidth, [int]$srcHeight, [int]$destX, [int]$destY, [int]$destWidth, [int]$destHeight )
    $destRect = new-object Drawing.Rectangle $destX, $destY, $destWidth, $destHeight
    $srcRect = new-object Drawing.Rectangle $srcX, $srcY, $srcWidth, $srcHeight
    $graphics.DrawImage($src, $destRect, $srcRect, $units)
}

DrawCroppedImage 8 0 8 8 8 0 8 8

$graphics.Dispose()
$bmp.Save("$pwd\1.png")

因此我可以重复它,而无需为每种作物再次重写所有代码。我想补充一个事实,如果你缩放它(最后两个整数= 16),但你想在没有任何插值的情况下进行它,你可以使用相同的函数,但多了两行:

function DrawCroppedImage {
    param( [int]$SrcX, [int]$SrcY, [int]$SrcWidth, [int]$SrcHeight, [int]$DestX, [int]$DestY, [int]$DestWidth, [int]$DestHeight )
    $DestRect = new-object Drawing.Rectangle $DestX, $DestY, $DestWidth, $DestHeight
    $SrcRect = new-object Drawing.Rectangle $SrcX, $SrcY, $SrcWidth, $SrcHeight
    //these two
    $graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::NearestNeighbor
    $graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::Half
}

发现通过这个线程 https://stackoverflow.com/questions/11456440/how-to-resize-a-bitmap-image-in-c-sharp-without-blending-or-filtering

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Powershell 在 System.Drawing 中使用 .NET .DrawImage 的相关文章

随机推荐