Skip to content

Instantly share code, notes, and snippets.

@greggman
Last active May 17, 2023 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggman/0fe9e5b538c62f767bbc004dd3f085f0 to your computer and use it in GitHub Desktop.
Save greggman/0fe9e5b538c62f767bbc004dd3f085f0 to your computer and use it in GitHub Desktop.
Crop Image
img, canvas {
display: block;
max-width: 400px;
margin-bottom: 5px;
border: 1px solid red;
}
/*bug-in-github-api-content-can-not-be-empty*/
function findEdge(edgeColor, width, height, pixels, x, y, perPixelDX, perPixelDY, perLineDX, perLineDY) {
//const mask = 0xFFFFFFFF;
//const mask = 0xFEFEFEFE;
//const mask = 0xFCFCFCFC;
//const mask = 0xF8F8F8F8;
const mask = 0xF0F0F0F0;
edgeColor &= mask;
while (x >= 0 && y >= 0 && x < width && y < height) {
let lineX = x;
let lineY = y;
while (lineX >= 0 && lineY >= 0 && lineX < width && lineY < height) {
const offset = lineY * width + lineX;
const pixel = pixels[offset] & mask;
if (pixel !== edgeColor) {
return [x, y];
}
lineX += perPixelDX;
lineY += perPixelDY;
}
x += perLineDX;
y += perLineDY;
}
return [x, y];
}
async function main() {
const url = 'https://live.staticflickr.com/65535/50461424808_96c3f5aa86_b.jpg';
const res = await fetch(url);
const blob = await res.blob();
const img = new Image();
img.src = URL.createObjectURL(blob)
await img.decode();
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const {width, height} = canvas;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const imgData = ctx.getImageData(0, 0, width, height);
const pixels = new Uint32Array(imgData.data.buffer);
const edgeColor = pixels[0];
// x y dx dy lineDx lineDY
const left = findEdge(edgeColor, width, height, pixels, 0 , 0 , 0, 1, 1, 0)[0];
const right = findEdge(edgeColor, width, height, pixels, width - 1, 0 , 0, 1, -1, 0)[0];
const top = findEdge(edgeColor, width, height, pixels, 0 , 0 , 1, 0, 0, 1)[1];
const bottom = findEdge(edgeColor, width, height, pixels, 0 , height - 1, 1, 0, 0, -1)[1];
const w = right - left + 1;
const h = bottom - top + 1;
console.log(0, 0, width, height);
console.log(left, top, right, bottom);
canvas.width = w;
canvas.height = h;
ctx.drawImage(img,
left, top, w, h,
0, 0, w, h);
document.body.appendChild(img);
document.body.appendChild(canvas);
}
main();
{"name":"Crop Image","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment