trimEdges returns a new image with solid color borders of the image removed. The pixel at the top left corner is used to match the border color.
(img image.Image)
| 328 | // trimEdges returns a new image with solid color borders of the image removed. |
| 329 | // The pixel at the top left corner is used to match the border color. |
| 330 | func trimEdges(img image.Image) image.Image { |
| 331 | bounds := img.Bounds() |
| 332 | minX, minY, maxX, maxY := bounds.Max.X, bounds.Max.Y, bounds.Min.X, bounds.Min.Y |
| 333 | |
| 334 | // Get the color of the first pixel (top-left corner) |
| 335 | baseColor := img.At(bounds.Min.X, bounds.Min.Y) |
| 336 | |
| 337 | // Check each pixel and find the bounding box of non-matching pixels |
| 338 | for y := bounds.Min.Y; y < bounds.Max.Y; y++ { |
| 339 | for x := bounds.Min.X; x < bounds.Max.X; x++ { |
| 340 | if img.At(x, y) != baseColor { // Non-matching pixel |
| 341 | if x < minX { |
| 342 | minX = x |
| 343 | } |
| 344 | if y < minY { |
| 345 | minY = y |
| 346 | } |
| 347 | if x > maxX { |
| 348 | maxX = x |
| 349 | } |
| 350 | if y > maxY { |
| 351 | maxY = y |
| 352 | } |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | // If no non-matching pixels are found, return the original image |
| 358 | if minX >= maxX || minY >= maxY { |
| 359 | return img |
| 360 | } |
| 361 | |
| 362 | // Crop the image to the bounding box of non-matching pixels |
| 363 | return imaging.Crop(img, image.Rect(minX, minY, maxX+1, maxY+1)) |
| 364 | } |
no outgoing calls