From 8bee2894351444d5a7ef132fa7e1213c48d41ebf Mon Sep 17 00:00:00 2001 From: treeform Date: Mon, 1 Aug 2022 17:07:48 -0700 Subject: [PATCH] Add cropAlpha. --- src/pixie/images.nim | 30 ++++++++++++++++++++++++++++ tests/images/cropHeart.png | Bin 0 -> 1067 bytes tests/test_images.nim | 39 +++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 tests/images/cropHeart.png diff --git a/src/pixie/images.nim b/src/pixie/images.nim index eef3c14..3af36ca 100644 --- a/src/pixie/images.nim +++ b/src/pixie/images.nim @@ -751,5 +751,35 @@ proc superImage*(image: Image, x, y, w, h: int): Image {.raises: [PixieError].} result = newImage(w, h) result.draw(image, translate(vec2(-x.float32, -y.float32)), OverwriteBlend) +proc cropAlpha*(image: Image): (Image, Rect) = + ## Crops the alpha off the edges of an image. + ## Returns the new cropped image and the rectangle it used for cropping. + var + xMin = image.width + xMax = 0 + yMin = image.height + yMax = 0 + # Find the crop coordinates. + for y in 0 ..< image.height: + for x in 0 ..< image.width: + if image.unsafe[x, y].a != 0: + xMin = min(xMin, x) + xMax = max(xMax, x + 1) + yMin = min(yMin, y) + yMax = max(yMax, y + 1) + if xMax <= xMin or yMax <= yMin: + raise newException(PixieError, "Cannot cropAlpha fully transparent image") + let + corpImage = newImage(xMax - xMin, yMax - yMin) + cropRect = rect( + xMin.float32, + yMin.float32, + corpImage.width.float32, + corpImage.height.float32 + ) + # Draw the bigger image into the cropped image. + corpImage.draw(image, translate(vec2(-xMin.float32, -yMin.float32))) + return (corpImage, cropRect) + when defined(release): {.pop.} diff --git a/tests/images/cropHeart.png b/tests/images/cropHeart.png new file mode 100644 index 0000000000000000000000000000000000000000..ea21adbf3405d194da0cdcaddccb450bbfb43241 GIT binary patch literal 1067 zcmV+`1l0S9P)NklMh_Cu zo8UpjwrY|^C?Vj*Lv2ZE3@KF0>LHf6y4lQEp4pwHo9yn)?9OaktPhU92jD7DS$7CEuU0i(s&y>-9EM#9`4+%#cUm;;u4=ke>sa*7i;pw= zpg87EiW0>!{^aAl;yg63$t0sLd;QM>wc$4CI4wZNZ^7 zuizcwpte!yK)ANxP@7lqj&M-h021V{ZJWruaIbg}h|RarLOk+ap}?0=-v&@DPS%#5Q_afFkQ2 z=cO@v+4EQnAhQ$CRP~B?qj%96diDI(0uW1+rvW@?-HQnD+;Woq|Gh?C0Lf>ch-$8O zx7Se3(c}MZ)de7CPx71sORRed0hZ`(tEX)NXVXKgIV}T_#L{jC*UDJef26g zm-_;$7rZ@RRDWa-dwtLP&~X5g1sr>R{G=#O@cV4;HKD{a_WbxTdzzdHMI-?{togA^ zmY9@4{_*xaxW{`u?#n=R<`qa7|dhv`QcG9@kM4c>p56j6Yub_s