Java BufferedImage to Shape imageToShape(BufferedImage image)

Here you can find the source of imageToShape(BufferedImage image)

Description

image To Shape

License

Open Source License

Declaration

public static Shape imageToShape(BufferedImage image) 

Method Source Code

//package com.java2s;
/*//from   w w  w .j a  va 2 s  .  co m
 *  Copyright (C) 2010-2014 JPEXS
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.image.BufferedImage;

public class Main {
    public static Shape imageToShape(BufferedImage image) {
        Area area = new Area();
        Rectangle rectangle = new Rectangle();
        int y1, y2;
        for (int x = 0; x < image.getWidth(); x++) {
            y1 = Integer.MAX_VALUE;
            y2 = -1;
            for (int y = 0; y < image.getHeight(); y++) {
                int rgb = image.getRGB(x, y);
                rgb = rgb >>> 24;
                if (rgb > 0) {
                    if (y1 == Integer.MAX_VALUE) {
                        y1 = y;
                        y2 = y;
                    }
                    if (y > (y2 + 1)) {
                        rectangle.setBounds(x, y1, 1, y2 - y1 + 1);
                        area.add(new Area(rectangle));
                        y1 = y;
                    }
                    y2 = y;
                }
            }
            if ((y2 - y1) >= 0) {
                rectangle.setBounds(x, y1, 1, y2 - y1 + 1);
                area.add(new Area(rectangle));
            }
        }
        return area;
    }
}

Related

  1. imageToShape(BufferedImage image)
  2. imageToShapeOld(BufferedImage image)