Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a way to crop all 4 sides, using the color from the very top-left pixel as the baseline, and allow for a tolerance of color variation so that noise in the image won't make the crop useless</p> <pre><code>public BufferedImage getCroppedImage(BufferedImage source, double tolerance) { // Get our top-left pixel color as our "baseline" for cropping int baseColor = source.getRGB(0, 0); int width = source.getWidth(); int height = source.getHeight(); int topY = Integer.MAX_VALUE, topX = Integer.MAX_VALUE; int bottomY = -1, bottomX = -1; for(int y=0; y&lt;height; y++) { for(int x=0; x&lt;width; x++) { if (colorWithinTolerance(baseColor, source.getRGB(x, y), tolerance)) { if (x &lt; topX) topX = x; if (y &lt; topY) topY = y; if (x &gt; bottomX) bottomX = x; if (y &gt; bottomY) bottomY = y; } } } BufferedImage destination = new BufferedImage( (bottomX-topX+1), (bottomY-topY+1), BufferedImage.TYPE_INT_ARGB); destination.getGraphics().drawImage(source, 0, 0, destination.getWidth(), destination.getHeight(), topX, topY, bottomX, bottomY, null); return destination; } private boolean colorWithinTolerance(int a, int b, double tolerance) { int aAlpha = (int)((a &amp; 0xFF000000) &gt;&gt;&gt; 24); // Alpha level int aRed = (int)((a &amp; 0x00FF0000) &gt;&gt;&gt; 16); // Red level int aGreen = (int)((a &amp; 0x0000FF00) &gt;&gt;&gt; 8); // Green level int aBlue = (int)(a &amp; 0x000000FF); // Blue level int bAlpha = (int)((b &amp; 0xFF000000) &gt;&gt;&gt; 24); // Alpha level int bRed = (int)((b &amp; 0x00FF0000) &gt;&gt;&gt; 16); // Red level int bGreen = (int)((b &amp; 0x0000FF00) &gt;&gt;&gt; 8); // Green level int bBlue = (int)(b &amp; 0x000000FF); // Blue level double distance = Math.sqrt((aAlpha-bAlpha)*(aAlpha-bAlpha) + (aRed-bRed)*(aRed-bRed) + (aGreen-bGreen)*(aGreen-bGreen) + (aBlue-bBlue)*(aBlue-bBlue)); // 510.0 is the maximum distance between two colors // (0,0,0,0 -&gt; 255,255,255,255) double percentAway = distance / 510.0d; return (percentAway &gt; tolerance); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload