* Autocrop same color borders from this image. * This function will attempt to crop out transparent pixels from the image. * * @example * ```ts * import { Jimp } from "jimp"; * * const image = await Jimp.read("test/image.png"); * const cropped = image.autocrop(); * ```
(image: I, options: AutocropOptions = {})
| 97 | * ``` |
| 98 | */ |
| 99 | autocrop<I extends JimpClass>(image: I, options: AutocropOptions = {}) { |
| 100 | const { |
| 101 | tolerance = 0.0002, |
| 102 | cropOnlyFrames = true, |
| 103 | cropSymmetric = false, |
| 104 | leaveBorder = 0, |
| 105 | ignoreSides: ignoreSidesArg, |
| 106 | } = typeof options === "number" |
| 107 | ? ({ tolerance: options } as AutocropComplexOptions) |
| 108 | : AutocropComplexOptionsSchema.parse(options); |
| 109 | const w = image.bitmap.width; |
| 110 | const h = image.bitmap.height; |
| 111 | const minPixelsPerSide = 1; // to avoid cropping completely the image, resulting in an invalid 0 sized image |
| 112 | |
| 113 | // i.e. north and south / east and west are cropped by the same value |
| 114 | const ignoreSides = { |
| 115 | north: false, |
| 116 | south: false, |
| 117 | east: false, |
| 118 | west: false, |
| 119 | ...ignoreSidesArg, |
| 120 | }; |
| 121 | |
| 122 | /** |
| 123 | * All borders must be of the same color as the top left pixel, to be cropped. |
| 124 | * It should be possible to crop borders each with a different color, |
| 125 | * but since there are many ways for corners to intersect, it would |
| 126 | * introduce unnecessary complexity to the algorithm. |
| 127 | */ |
| 128 | |
| 129 | // scan each side for same color borders |
| 130 | let colorTarget = image.getPixelColor(0, 0); // top left pixel color is the target color |
| 131 | const rgba1 = intToRGBA(colorTarget); |
| 132 | |
| 133 | // for north and east sides |
| 134 | let northPixelsToCrop = 0; |
| 135 | let eastPixelsToCrop = 0; |
| 136 | let southPixelsToCrop = 0; |
| 137 | let westPixelsToCrop = 0; |
| 138 | |
| 139 | // north side (scan rows from north to south) |
| 140 | colorTarget = image.getPixelColor(0, 0); |
| 141 | if (!ignoreSides.north) { |
| 142 | north: for (let y = 0; y < h - minPixelsPerSide; y++) { |
| 143 | for (let x = 0; x < w; x++) { |
| 144 | const colorXY = image.getPixelColor(x, y); |
| 145 | const rgba2 = intToRGBA(colorXY); |
| 146 | |
| 147 | if (colorDiff(rgba1, rgba2) > tolerance) { |
| 148 | // this pixel is too distant from the first one: abort this side scan |
| 149 | break north; |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | // this row contains all pixels with the same color: increment this side pixels to crop |
| 154 | northPixelsToCrop++; |
| 155 | } |
| 156 | } |
nothing calls this directly
no test coverage detected
searching dependent graphs…