Example usage for java.awt.image BufferedImage setRGB

List of usage examples for java.awt.image BufferedImage setRGB

Introduction

In this page you can find the example usage for java.awt.image BufferedImage setRGB.

Prototype

public void setRGB(int x, int y, int rgb) 

Source Link

Document

Sets a pixel in this BufferedImage to the specified RGB value.

Usage

From source file:net.cloudkit.relaxation.VerifyImage.java

public void getFont(BufferedImage image, int x, int y, BufferedImage draw, BufferedImage outDraw) {
    int w = image.getWidth();
    int h = image.getHeight();
    int c = getRed(image.getRGB(x, y));
    if (c != 255) {
        int c1 = x == 0 ? 255 : getRed(image.getRGB(x - 1, y));
        int c2 = x == w - 1 ? 255 : getRed(image.getRGB(x + 1, y));
        int c3 = y == 0 ? 255 : getRed(image.getRGB(x, y - 1));
        int c4 = y == h - 1 ? 255 : getRed(image.getRGB(x, y + 1));
        int c5 = x != 0 && y != 0 ? getRed(image.getRGB(x - 1, y - 1)) : 255;
        int c6 = x != w - 1 && y != 0 ? getRed(image.getRGB(x + 1, y - 1)) : 255;
        int c7 = x != 0 && y != h - 1 ? getRed(image.getRGB(x - 1, y + 1)) : 255;
        int c8 = x != w - 1 && y != h - 1 ? getRed(image.getRGB(x + 1, y + 1)) : 255;
        outDraw.setRGB(x, y, image.getRGB(x, y));
        draw.setRGB(x, y, Color.WHITE.getRGB());
        ++this.count;
        if (c1 != 255) {
            this.getFont(image, x - 1, y, draw, outDraw);
        }//  ww  w .  j  a  v a  2  s. com

        if (c2 != 255) {
            this.getFont(image, x + 1, y, draw, outDraw);
        }

        if (c3 != 255) {
            this.getFont(image, x, y - 1, draw, outDraw);
        }

        if (c4 != 255) {
            this.getFont(image, x, y + 1, draw, outDraw);
        }

        if (c5 != 255) {
            this.getFont(image, x - 1, y - 1, draw, outDraw);
        }

        if (c6 != 255) {
            this.getFont(image, x + 1, y - 1, draw, outDraw);
        }

        if (c7 != 255) {
            this.getFont(image, x - 1, y + 1, draw, outDraw);
        }

        if (c8 != 255) {
            this.getFont(image, x + 1, y + 1, draw, outDraw);
        }

    }
}

From source file:org.jtalks.jcommune.service.nontransactional.ImageConverter.java

/**
 * Creates a <code>BufferedImage</code> from an <code>Image</code>. This method can
 * function on a completely headless system. This especially includes Linux and Unix systems
 * that do not have the X11 libraries installed, which are required for the AWT subsystem to
 * operate. The resulting image will be smoothly scaled using bilinear filtering.
 *
 * @param source    The image to convert
 * @param width     The desired image width
 * @param height    The desired image height
 * @param imageType int code RGB or ARGB
 * @return bufferedImage The resized image
 *///from   w ww.  j a  v  a 2  s .c  o  m
private BufferedImage createBufferedImage(BufferedImage source, int imageType, int width, int height) {
    BufferedImage bufferedImage = new BufferedImage(width, height, imageType);

    int sourceX;
    int sourceY;

    double scaleX = (double) width / source.getWidth();
    double scaleY = (double) height / source.getHeight();

    int x1;
    int y1;

    double xDiff;
    double yDiff;

    int rgb;
    int rgb1;
    int rgb2;

    for (int y = 0; y < height; y++) {
        sourceY = y * source.getHeight() / bufferedImage.getHeight();
        yDiff = y / scaleY - sourceY;

        for (int x = 0; x < width; x++) {
            sourceX = x * source.getWidth() / bufferedImage.getWidth();
            xDiff = x / scaleX - sourceX;

            x1 = Math.min(source.getWidth() - 1, sourceX + 1);
            y1 = Math.min(source.getHeight() - 1, sourceY + 1);

            rgb1 = getRGBInterpolation(source.getRGB(sourceX, sourceY), source.getRGB(x1, sourceY), xDiff);
            rgb2 = getRGBInterpolation(source.getRGB(sourceX, y1), source.getRGB(x1, y1), xDiff);

            rgb = getRGBInterpolation(rgb1, rgb2, yDiff);

            bufferedImage.setRGB(x, y, rgb);
        }
    }

    return bufferedImage;
}

From source file:org.apache.pdfbox.rendering.TestPDFToImage.java

/**
 * Get the difference between two images, identical colors are set to white, differences are
 * xored, the highest bit of each color is reset to avoid colors that are too light
 *
 * @param bim1//from   w  w  w .j a  v  a 2s  .c  om
 * @param bim2
 * @return If the images are different, the function returns a diff image If the images are
 * identical, the function returns null If the size is different, a black border on the botton
 * and the right is created
 *
 * @throws IOException
 */
private BufferedImage diffImages(BufferedImage bim1, BufferedImage bim2) throws IOException {
    int minWidth = Math.min(bim1.getWidth(), bim2.getWidth());
    int minHeight = Math.min(bim1.getHeight(), bim2.getHeight());
    int maxWidth = Math.max(bim1.getWidth(), bim2.getWidth());
    int maxHeight = Math.max(bim1.getHeight(), bim2.getHeight());
    BufferedImage bim3 = null;
    if (minWidth != maxWidth || minHeight != maxHeight) {
        bim3 = createEmptyDiffImage(minWidth, minHeight, maxWidth, maxHeight);
    }
    for (int x = 0; x < minWidth; ++x) {
        for (int y = 0; y < minHeight; ++y) {
            int rgb1 = bim1.getRGB(x, y);
            int rgb2 = bim2.getRGB(x, y);
            if (rgb1 != rgb2
                    // don't bother about differences of 1 color step
                    && (Math.abs((rgb1 & 0xFF) - (rgb2 & 0xFF)) > 1
                            || Math.abs(((rgb1 >> 8) & 0xFF) - ((rgb2 >> 8) & 0xFF)) > 1
                            || Math.abs(((rgb1 >> 16) & 0xFF) - ((rgb2 >> 16) & 0xFF)) > 1)) {
                if (bim3 == null) {
                    bim3 = createEmptyDiffImage(minWidth, minHeight, maxWidth, maxHeight);
                }
                int r = Math.abs((rgb1 & 0xFF) - (rgb2 & 0xFF));
                int g = Math.abs((rgb1 & 0xFF00) - (rgb2 & 0xFF00));
                int b = Math.abs((rgb1 & 0xFF0000) - (rgb2 & 0xFF0000));
                bim3.setRGB(x, y, 0xFFFFFF - (r | g | b));
            } else {
                if (bim3 != null) {
                    bim3.setRGB(x, y, Color.WHITE.getRGB());
                }
            }
        }
    }
    return bim3;
}

From source file:playground.christoph.evacuation.analysis.EvacuationTimePictureWriter.java

private ScreenOverlayType createHistogram(String transportMode, Map<Id, Double> evacuationTimes)
        throws IOException {

    /*/*from   w  w w.j ava2s  .c  om*/
     * Remove NaN entries from the List
     */
    List<Double> listWithoutNaN = new ArrayList<Double>();
    for (Double d : evacuationTimes.values())
        if (!d.isNaN())
            listWithoutNaN.add(d);

    /*
     * If trip with significant to high evacuation times should be cut off
     */
    if (limitMaxEvacuationTime) {
        double cutOffValue = meanEvacuationTime + standardDeviation * evacuationTimeCutOffFactor;
        ListIterator<Double> iter = listWithoutNaN.listIterator();
        while (iter.hasNext()) {
            double value = iter.next();
            if (value > cutOffValue)
                iter.remove();
        }
    }

    double[] array = new double[listWithoutNaN.size()];
    int i = 0;
    for (double d : listWithoutNaN)
        array[i++] = d;

    JFreeChart chart = createHistogramChart(transportMode, array);
    BufferedImage chartImage = chart.createBufferedImage(OVERALLHISTOGRAMWIDTH, OVERALLHISTOGRAMHEIGHT);
    BufferedImage image = new BufferedImage(OVERALLHISTOGRAMWIDTH, OVERALLHISTOGRAMHEIGHT,
            BufferedImage.TYPE_4BYTE_ABGR);

    // clone image and set alpha value
    for (int x = 0; x < OVERALLHISTOGRAMWIDTH; x++) {
        for (int y = 0; y < OVERALLHISTOGRAMHEIGHT; y++) {
            int rgb = chartImage.getRGB(x, y);
            Color c = new Color(rgb);
            int r = c.getRed();
            int b = c.getBlue();
            int g = c.getGreen();
            int argb = 225 << 24 | r << 16 | g << 8 | b; // 225 as transparency value
            image.setRGB(x, y, argb);
        }
    }

    byte[] imageBytes = bufferedImageToByteArray(image);
    this.kmzWriter.addNonKMLFile(imageBytes, transportMode + OVERALLHISTROGRAM);

    ScreenOverlayType overlay = kmlObjectFactory.createScreenOverlayType();
    LinkType icon = kmlObjectFactory.createLinkType();
    icon.setHref(transportMode + OVERALLHISTROGRAM);
    overlay.setIcon(icon);
    overlay.setName("Histogram " + transportMode);
    // place the image top right
    Vec2Type overlayXY = kmlObjectFactory.createVec2Type();
    overlayXY.setX(0.0);
    overlayXY.setY(1.0);
    overlayXY.setXunits(UnitsEnumType.FRACTION);
    overlayXY.setYunits(UnitsEnumType.FRACTION);
    overlay.setOverlayXY(overlayXY);
    Vec2Type screenXY = kmlObjectFactory.createVec2Type();
    screenXY.setX(0.02);
    screenXY.setY(0.98);
    screenXY.setXunits(UnitsEnumType.FRACTION);
    screenXY.setYunits(UnitsEnumType.FRACTION);
    overlay.setScreenXY(screenXY);
    return overlay;
}

From source file:pack1.test.java

@WebMethod(operationName = "convert")
public String convert(@WebParam(name = "encodedImageStr") String encodedImageStr,
        @WebParam(name = "fileName") String fileName, @WebParam(name = "AOR") String AOR,
        @WebParam(name = "val") int value) {
    System.out.println("Value" + value);
    FileOutputStream imageOutFile = null;
    try {//from   w  w w.  ja  v  a 2  s  .c  o  m
        Connection con, con1;
        Statement stmtnew = null;
        area = Double.parseDouble(AOR);
        //int val=Integer.parseInt(value);
        System.out.println("connecting");
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        System.out.println("connected");
        con = DriverManager.getConnection("jdbc:odbc:test");
        System.out.println(" driver loaded in connection.jsp");
        stmtnew = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        // Decode String using Base64 Class
        byte[] imageByteArray = encodedImageStr.getBytes();
        // Write Image into File system - Make sure you update the path
        imageOutFile = new FileOutputStream(
                "C:/Users/Kushagr Jolly/Documents/NetBeansProjects/webservice/IASRI/cropped" + fileName);
        imageOutFile.write(imageByteArray);
        imageOutFile.close();
        System.out.println("Image Successfully Stored");
        FileInputStream leafPicPath = new FileInputStream(
                "C:/Users/Kushagr Jolly/Documents/NetBeansProjects/webservice/IASRI/cropped" + fileName);
        BufferedImage cat;
        int height, width;
        cat = ImageIO.read(leafPicPath);
        height = cat.getHeight();
        width = cat.getWidth();
        for (int w = 0; w < cat.getWidth(); w++) {

            for (int h = 0; h < cat.getHeight(); h++) {
                // BufferedImage.getRGB() saves the colour of the pixel as a single integer.
                // use Color(int) to grab the RGB values individually.

                Color color = new Color(cat.getRGB(w, h));

                // use the RGB values to get their average.

                int averageColor = ((color.getRed() + color.getGreen() + color.getBlue()) / 3);
                // create a new Color object using the average colour as the red, green and blue

                // colour values

                Color avg = new Color(averageColor, averageColor, averageColor);

                // set the pixel at that position to the new Color object using Color.getRGB().            

                cat.setRGB(w, h, avg.getRGB());

            }

        }
        String greyPicPath = "C:/Users/Kushagr Jolly/Documents/NetBeansProjects/webservice/IASRI/greyscale"
                + fileName;
        greyPicPath = greyPicPath.trim();
        File outputfile = new File(greyPicPath);
        ImageIO.write(cat, "jpg", outputfile);
        System.out.println("Image is successfully converted to grayscale");

        String binPicPath = "C:/Users/Kushagr Jolly/Documents/NetBeansProjects/webservice/IASRI/binary"
                + fileName;
        File f2 = new File(binPicPath);
        System.out.println("1");
        ImageProcessor ip;
        ImagePlus imp = new ImagePlus(greyPicPath);
        System.out.println("2");
        ip = imp.getProcessor();
        ip.invertLut();
        ip.autoThreshold();
        System.out.println("3");
        BufferedImage bf = ip.getBufferedImage();
        System.out.println("4");
        ImageIO.write(bf, "jpg", f2);
        System.out.println("Image is successfully converted to binary image");
        if (choice == 1) {
            String Inserted1 = "insert into test (PhyAOR) values ('" + area + "')";
            System.out.println("InsertedQuery" + Inserted1);
            stmtnew.executeUpdate(Inserted1);
            Statement stmt = con.createStatement();
            ResultSet rs = null;
            String ID = "select MAX(id) as id from test";
            System.out.println("Query" + ID);
            rs = stmt.executeQuery(ID);
            while (rs.next()) {
                id = rs.getInt("id");
            }
            String Inserted2 = "update test set fileName0=? where id=?";
            PreparedStatement ps = con.prepareStatement(Inserted2);
            ps.setString(1, fileName);
            ps.setDouble(2, id);
            int rt = ps.executeUpdate();
            choice++;
        }
        System.out.println(choice);
        if (value == 1) {

            int count = countblackpixel(binPicPath);
            calculatepixA(count, area);
            //returnVal=value+"/"+count+"/"+OnepixArea;

        } else if (value == 2) {

            int flag = countblackpixel(binPicPath);
            // calculatepixA(flag, area);
            leafarea0(flag, area);
            //returnVal=value+"/"+flag+"/"+OnepixArea+"/"+leafArea0;
            //System.out.println(returnVal);
        } else if (value == 3) {
            String Inserted3 = "update test set fileName180=? where id=?";
            PreparedStatement ps1 = con.prepareStatement(Inserted3);
            ps1.setString(1, fileName);
            ps1.setDouble(2, id);
            int rt = ps1.executeUpdate();
            int black = countblackpixel(binPicPath);
            leafarea180(area, black);
            finalarea();
            Statement stmt = con.createStatement();
            ResultSet rs = null;
            String finalans = "select PhyAOR,onePixA,leafarea0,leafarea180,finalleafarea from test where id="
                    + id + "";
            rs = stmt.executeQuery(finalans);
            while (rs.next()) {
                returnVal = rs.getString("PhyAOR") + "/" + rs.getString("onePixA") + "/"
                        + rs.getString("leafarea0") + "/" + rs.getString("leafarea180") + "/"
                        + rs.getString("finalleafarea");
            }
            //returnVal=value+"/"+black+"/"+OnepixArea+"/"+leafArea180+"/"+Leaf_Area;
        } else if (value == 4) {
            finalarea();

        }
        imageOutFile.close();
    } catch (Exception ex) {
        Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println(ex);

    }
    return returnVal;

}

From source file:net.spfbl.core.Core.java

public static File getQRCodeTempFile(String codigo) throws Exception {
    BitMatrix matrix = qrCodeWriter.encode(codigo, com.google.zxing.BarcodeFormat.QR_CODE, 256, 256);
    int width = matrix.getWidth();
    int height = matrix.getHeight();
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            if (!matrix.get(x, y)) {
                image.setRGB(x, y, Color.WHITE.getRGB());
            }//w w w  .java  2 s .c o  m
        }
    }
    File file = File.createTempFile(Long.toString(Server.getNewUniqueTime()), ".png");
    ImageIO.write(image, "PNG", file);
    Server.logTrace("QRCode temp file created at " + file.getAbsolutePath() + ".");
    file.deleteOnExit();
    return file;
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static BufferedImage cylindricalMapping(BufferedImage img, double f) {
    if (img == null) {
        return null;
    }//from ww  w  .  java  2s  .  c o  m

    int w = img.getWidth();
    int h = img.getHeight();
    BufferedImage out = new BufferedImage(w, h, img.getType());
    //System.out.println("w:"+w+", h:"+h);

    int x0 = (int) Math.floor(w / 2) + 1;
    int y0 = (int) Math.floor(h / 2) + 1;

    double tmax = Math.atan2((double) (w - x0), f);
    double tmin = Math.atan2(-((double) x0), f);
    double tstep = (tmax - tmin) / ((double) w);

    double vmax = ((double) (h - y0)) / f;
    double vmin = (-(double) y0) / f;
    double vstep = (vmax - vmin) / ((double) h);

    double theta, tan, cos;
    int x, y;

    for (int t = 0; t < w; t++) {
        theta = tmin + (double) t * tstep;
        tan = Math.tan(theta);
        cos = Math.cos(theta);
        x = (int) Math.round(f * tan) + x0;
        for (int v = 0; v < h; v++) {
            //nearest neighbour---------------------------------------
            //x = (int)Math.round(f*tan) + x0;
            y = (int) Math.round((vmin + (double) v * vstep) * f / cos) + y0;
            if (x >= 0 && y >= 0 && x < w && y < h) {
                //piksel nowy x,y = piksel stary xd,yd
                out.setRGB(t, v, img.getRGB(x, y));
            }
            //---------------------------------------------------------
        }
    }
    return out;
}

From source file:org.kurento.test.base.BrowserTest.java

public String ocr(BufferedImage imgBuff) {
    String parsedOut = null;/*w w w.  ja v  a 2  s  .c  o m*/

    try {
        // Color image to pure black and white
        for (int x = 0; x < imgBuff.getWidth(); x++) {
            for (int y = 0; y < imgBuff.getHeight(); y++) {
                Color color = new Color(imgBuff.getRGB(x, y));
                int red = color.getRed();
                int green = color.getBlue();
                int blue = color.getGreen();
                if (red + green + blue > OCR_COLOR_THRESHOLD) {
                    red = green = blue = 0; // Black
                } else {
                    red = green = blue = 255; // White
                }
                Color col = new Color(red, green, blue);
                imgBuff.setRGB(x, y, col.getRGB());
            }
        }

        // OCR recognition
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(imgBuff, "png", baos);
        byte[] imageBytes = baos.toByteArray();

        TessBaseAPI api = new TessBaseAPI();
        api.Init(null, "eng");
        ByteBuffer imgBB = ByteBuffer.wrap(imageBytes);

        PIX image = pixReadMem(imgBB, imageBytes.length);
        api.SetImage(image);

        // Get OCR result
        BytePointer outText = api.GetUTF8Text();

        // Destroy used object and release memory
        api.End();
        api.close();
        outText.deallocate();
        pixDestroy(image);

        // OCR corrections
        parsedOut = outText.getString().replaceAll("l", "1").replaceAll("Z", "2").replaceAll("O", "0")
                .replaceAll("B", "8").replaceAll("G", "6").replaceAll("S", "8").replaceAll("'", "")
                .replaceAll("", "").replaceAll("\\.", ":").replaceAll("E", "8").replaceAll("o", "0")
                .replaceAll("", "0").replaceAll("?", "6").replaceAll("", "5").replaceAll("I", "1")
                .replaceAll("T", "7").replaceAll("", "").replaceAll("U", "0").replaceAll("D", "0");
        if (parsedOut.length() > 7) {
            parsedOut = parsedOut.substring(0, 7) + ":" + parsedOut.substring(8, parsedOut.length());
        }
        parsedOut = parsedOut.replaceAll("::", ":");

        // Remove last part (number of frames)
        int iSpace = parsedOut.lastIndexOf(" ");
        if (iSpace != -1) {
            parsedOut = parsedOut.substring(0, iSpace);
        }
    } catch (IOException e) {
        log.warn("IOException in OCR", e);
    }
    return parsedOut;
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static BufferedImage sphericalMapping(BufferedImage img, double f) {
    if (img == null) {
        return null;
    }/*from  w ww .  j av a  2 s  .c om*/

    int w = img.getWidth();
    int h = img.getHeight();
    BufferedImage out = new BufferedImage(w, h, img.getType());
    //System.out.println("w:"+w+", h:"+h);

    int x0 = (int) Math.floor(w / 2) + 1;
    int y0 = (int) Math.floor(h / 2) + 1;

    double tmax = Math.atan2((double) (w - x0), f);
    double tmin = Math.atan2(-((double) x0), f);
    double tstep = (tmax - tmin) / ((double) w);

    double fimax = Math.atan2((double) (h - y0), Math.sqrt(f * f));
    double fimin = Math.atan2(-(double) y0, Math.sqrt(f * f));
    double fistep = (fimax - fimin) / ((double) h);
    //System.out.println("fimax:"+fimax+", fimin:"+fimin);

    double theta, tantheta, costheta, tanfi, phi;
    int x, y;

    for (int t = 0; t < w; t++) {
        theta = tmin + (double) t * tstep;
        tantheta = Math.tan(theta);
        x = (int) Math.round(f * tantheta) + x0;
        for (int fi = 0; fi < h; fi++) {
            //nearest neighbour---------------------------------------
            phi = fimin + (double) fi * fistep;
            tanfi = Math.tan(phi);
            //x = (int)Math.round(f*tantheta) + x0;
            y = (int) Math.round(Math.sqrt((x - x0) * (x - x0) + f * f) * tanfi) + y0;
            if (x >= 0 && y >= 0 && x < w && y < h) {
                //piksel nowy x,y = piksel stary xd,yd
                out.setRGB(t, fi, img.getRGB(x, y));
            }
            //---------------------------------------------------------
        }
    }
    return out;
}