Example usage for java.awt.image BufferedImage TYPE_INT_RGB

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

Introduction

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

Prototype

int TYPE_INT_RGB

To view the source code for java.awt.image BufferedImage TYPE_INT_RGB.

Click Source Link

Document

Represents an image with 8-bit RGB color components packed into integer pixels.

Usage

From source file:com.liusoft.dlog4j.action.PhotoAction.java

/**
 * /*from  ww w. jav  a2  s .  c  om*/
 * @param ctx
 * @param imgURL
 * @param orient
 * @return
 * @throws IOException
 */
protected boolean rotate(HttpContext ctx, String imgURL, int orient) throws IOException {
    PhotoSaver saver = this.getPhotoSaver();
    InputStream inImg = saver.read(ctx, imgURL);
    BufferedImage old_img = (BufferedImage) ImageIO.read(inImg);
    int width = old_img.getWidth();
    int height = old_img.getHeight();
    BufferedImage new_img = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = new_img.createGraphics();

    AffineTransform origXform = g2d.getTransform();
    AffineTransform newXform = (AffineTransform) (origXform.clone());
    // center of rotation is center of the panel
    double radian = 0;
    double xRot = 0;
    double yRot = 0;
    switch (orient) {
    case 3:
        radian = 180.0;
        xRot = width / 2.0;
        yRot = height / 2.0;
    case 6:
        radian = 90.0;
        xRot = height / 2.0;
        yRot = xRot;
        break;
    case 8:
        radian = 270.0;
        xRot = width / 2.0;
        yRot = xRot;
        break;
    default:
        return false;
    }
    newXform.rotate(Math.toRadians(radian), xRot, yRot);

    g2d.setTransform(newXform);
    // draw image centered in panel
    g2d.drawImage(old_img, 0, 0, null);
    // Reset to Original
    g2d.setTransform(origXform);
    OutputStream out = saver.write(ctx, imgURL);
    try {
        ImageIO.write(new_img, "JPG", out);
    } finally {
        out.close();
    }
    return true;
}

From source file:com.piketec.jenkins.plugins.tpt.publisher.PieChart.java

/**
 * Render the pie chart with the given height
 * //from ww  w  . j  a  v a  2 s.c o  m
 * @param height
 *          The height of the resulting image
 * @return The pie chart rendered as an image
 */
public BufferedImage render(int height) {
    BufferedImage image = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.scale(zoom, zoom);
    // fill background to white
    g2.setColor(Color.WHITE);
    g2.fill(new Rectangle(totalWidth, totalHeight));
    // prepare render hints
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

    // draw shadow image
    g2.drawImage(pieShadow.getImage(), 0, 0, pieShadow.getImageObserver());

    double start = 0;
    List<Arc2D> pies = new ArrayList<>();
    // pie segmente erzeugen und fuellen
    if (total == 0) {
        g2.setColor(BRIGHT_GRAY);
        g2.fillOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
        g2.setColor(Color.WHITE);
        g2.drawOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
    } else {
        for (Segment s : segments) {
            double portionDegrees = s.getPortion() / total;
            Arc2D pie = paintPieSegment(g2, start, portionDegrees, s.getColor());
            if (withSubSegments) {
                double smallRadius = radius * s.getSubSegmentRatio();
                paintPieSegment(g2, start, portionDegrees, smallRadius, s.getColor().darker());
            }
            start += portionDegrees;
            // portion degree jetzt noch als String (z.B. "17.3%" oder "20%" zusammenbauen)
            String p = String.format(Locale.ENGLISH, "%.1f", Math.rint(portionDegrees * 1000) / 10.0);
            p = removeSuffix(p, ".0"); // evtl. ".0" bei z.B. "25.0" abschneiden (-> "25")
            s.setPercent(p + "%");
            pies.add(pie);
        }
        // weissen Rahmen um die pie segmente zeichen
        g2.setColor(Color.WHITE);
        for (Arc2D pie : pies) {
            g2.draw(pie);
        }
    }
    // Legende zeichnen
    renderLegend(g2);
    // "xx%" Label direkt auf die pie segmente zeichen
    g2.setColor(Color.WHITE);
    float fontSize = 32f;
    g2.setFont(NORMALFONT.deriveFont(fontSize).deriveFont(Font.BOLD));
    start = 0;
    for (Segment s : segments) {
        if (s.getPortion() < 1E-6) {
            continue; // ignore segments with portions that are extremely small
        }
        double portionDegrees = s.getPortion() / total;
        double angle = start + portionDegrees / 2; // genau in der Mitte des Segments
        double xOffsetForCenteredTxt = 8 * s.getPercent().length(); // assume roughly 8px per char
        int x = (int) (centerX + 0.6 * radius * Math.sin(2 * Math.PI * angle) - xOffsetForCenteredTxt);
        int y = (int) (centerY - 0.6 * radius * Math.cos(2 * Math.PI * angle) + fontSize / 2);
        g2.drawString(s.getPercent(), x, y);
        start += portionDegrees;
    }
    return image;
}

From source file:jurls.core.utils.MatrixImage.java

public void draw(Data2D d, int cw, int ch, double minValue, double maxValue) {

    if ((cw == 0) || (ch == 0)) {
        image = null;/*from ww w.  j  av  a2s  .c om*/
        return;
    }

    if (image == null || image.getWidth() != cw || image.getHeight() != ch) {
        image = new BufferedImage(cw, ch, BufferedImage.TYPE_INT_RGB);
    }

    this.minValue = minValue;
    this.maxValue = maxValue;

    int w = image.getWidth();
    int h = image.getHeight();

    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            double value = d.getValue(i, j);
            pixel(image, j, i, value);
        }
    }

    repaint();
}

From source file:hudson.jbpm.PluginImpl.java

/**
 * Draws a JPEG for a process definition
 * /*from   w ww.j  a  v  a2s  .co  m*/
 * @param req
 * @param rsp
 * @param processDefinition
 * @throws IOException
 */
public void doProcessDefinitionImage(StaplerRequest req, StaplerResponse rsp,
        @QueryParameter("processDefinition") long processDefinition) throws IOException {

    JbpmContext context = getCurrentJbpmContext();
    ProcessDefinition definition = context.getGraphSession().getProcessDefinition(processDefinition);
    FileDefinition fd = definition.getFileDefinition();
    byte[] bytes = fd.getBytes("processimage.jpg");
    rsp.setContentType("image/jpeg");
    ServletOutputStream output = rsp.getOutputStream();

    BufferedImage loaded = ImageIO.read(new ByteArrayInputStream(bytes));
    BufferedImage aimg = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g = aimg.createGraphics();
    g.drawImage(loaded, null, 0, 0);
    g.dispose();
    ImageIO.write(aimg, "jpg", output);
    output.flush();
    output.close();
}

From source file:com.tremolosecurity.scale.totp.TotpController.java

@PostConstruct
public void init() {
    this.error = null;
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();/*from w w w .  j  a  v a2s  . c  o m*/

    this.scaleTotpConfig = (ScaleTOTPConfigType) commonConfig.getScaleConfig();

    this.login = request.getRemoteUser();

    UnisonUserData userData;
    try {
        userData = this.scaleSession.loadUserFromUnison(this.login,
                new AttributeData(scaleTotpConfig.getServiceConfiguration().getLookupAttributeName(),
                        scaleTotpConfig.getUiConfig().getDisplayNameAttribute(),
                        scaleTotpConfig.getAttributeName()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    this.user = userData.getUserObj();

    this.displayName = userData.getUserObj().getDisplayName();

    ScaleAttribute scaleAttr = userData.getUserObj().getAttrs().get(scaleTotpConfig.getAttributeName());
    if (scaleAttr == null) {
        if (logger.isDebugEnabled())
            logger.debug("no sattribute");
        this.error = "Token not found";
        return;
    }

    this.encryptedToken = scaleAttr.getValue();

    try {
        byte[] decryptionKeyBytes = Base64.decodeBase64(scaleTotpConfig.getDecryptionKey().getBytes("UTF-8"));
        SecretKey decryptionKey = new SecretKeySpec(decryptionKeyBytes, 0, decryptionKeyBytes.length, "AES");

        Gson gson = new Gson();
        Token token = gson.fromJson(new String(Base64.decodeBase64(this.encryptedToken.getBytes("UTF-8"))),
                Token.class);
        byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());
        IvParameterSpec spec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, decryptionKey, spec);

        String decryptedJSON = new String(
                cipher.doFinal(Base64.decodeBase64(token.getEncryptedRequest().getBytes("UTF-8"))));

        if (logger.isDebugEnabled())
            logger.debug(decryptedJSON);

        TOTPKey totp = gson.fromJson(decryptedJSON, TOTPKey.class);

        this.otpURL = "otpauth://totp/" + totp.getUserName() + "@" + totp.getHost() + "?secret="
                + totp.getSecretKey();

    } catch (Exception e) {
        e.printStackTrace();
        this.error = "Could not decrypt token";
    }

    try {
        int size = 250;
        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix byteMatrix = qrCodeWriter.encode(this.otpURL, BarcodeFormat.QR_CODE, size, size, hintMap);
        int CrunchifyWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();

        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
        graphics.setColor(Color.BLACK);

        for (int i = 0; i < CrunchifyWidth; i++) {
            for (int j = 0; j < CrunchifyWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageIO.write(image, "png", baos);

        this.encodedQRCode = new String(Base64.encodeBase64(baos.toByteArray()));
    } catch (Exception e) {
        e.printStackTrace();
        this.error = "Could not encode QR Code";
    }

}

From source file:com.hygenics.imaging.ImageCleanup.java

public byte[] reaverage(double factor, byte[] ibytes) {
    // tone red coloring
    BufferedImage color = BufferImage(ibytes);

    if (color != null) {
        BufferedImage averaged = new BufferedImage(color.getWidth(), color.getHeight(),
                BufferedImage.TYPE_INT_RGB);

        for (int i = 0; i < color.getWidth(); i++) {
            for (int j = 0; j < color.getHeight(); j++) {
                Color c = new Color(color.getRGB(i, j));

                averaged.setRGB(i, j,//from  ww  w .j ava 2  s .c om
                        new Color((int) Math.round(c.getRed() / factor), c.getGreen(), c.getBlue()).getRGB());
            }
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // convert to jpeg for compression
        try {
            // use apache to read to a buffered image with certain metadata
            // and then convert to a jpg
            ImageIO.write(averaged, "jpg", bos);
            return ibytes = bos.toByteArray();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return ibytes;

}

From source file:com.piaoyou.util.ImageUtil.java

/**
 * @todo: xem lai ham nay, neu kich thuoc nho hon max thi ta luu truc tiep
 *          inputStream xuong thumbnailFile luon
 *
 * This method create a thumbnail and reserve the ratio of the output image
 * NOTE: This method closes the inputStream after it have done its work.
 *
 * @param inputStream     the stream of a jpeg file
 * @param outputStream    the output stream
 * @param maxWidth        the maximum width of the image
 * @param maxHeight       the maximum height of the image
 * @throws IOException//from   w w  w .ja  v  a2 s.  c  o  m
 * @throws BadInputException
 */
public static void createThumbnail(InputStream inputStream, OutputStream outputStream, int maxWidth,
        int maxHeight) throws IOException {

    if (inputStream == null) {
        throw new IllegalArgumentException("inputStream must not be null.");
    }
    if (outputStream == null) {
        throw new IllegalArgumentException("outputStream must not be null.");
    }

    //boolean useSun = false;
    if (maxWidth <= 0) {
        throw new IllegalArgumentException("maxWidth must >= 0");
    }
    if (maxHeight <= 0) {
        throw new IllegalArgumentException("maxHeight must >= 0");
    }

    try {
        //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(inputStream);
        //BufferedImage srcImage = decoder.decodeAsBufferedImage();
        byte[] srcByte = FileUtil.getBytes(inputStream);
        InputStream is = new ByteArrayInputStream(srcByte);
        //ImageIcon imageIcon = new ImageIcon(srcByte);
        //Image srcImage = imageIcon.getImage();

        BufferedImage srcImage = ImageIO.read(is);
        if (srcImage == null) {
            throw new IOException("Cannot decode image. Please check your file again.");
        }

        int imgWidth = srcImage.getWidth();
        int imgHeight = srcImage.getHeight();
        //          imgWidth or imgHeight could be -1, which is considered as an assertion
        AssertionUtil.doAssert((imgWidth > 0) && (imgHeight > 0),
                "Assertion: ImageUtil: cannot get the image size.");
        // Set the scale.
        AffineTransform tx = new AffineTransform();
        if ((imgWidth > maxWidth) || (imgHeight > maxHeight)) {
            double scaleX = (double) maxWidth / imgWidth;
            double scaleY = (double) maxHeight / imgHeight;
            double scaleRatio = (scaleX < scaleY) ? scaleX : scaleY;
            imgWidth = (int) (imgWidth * scaleX);
            imgWidth = (imgWidth == 0) ? 1 : imgWidth;
            imgHeight = (int) (imgHeight * scaleY);
            imgHeight = (imgHeight == 0) ? 1 : imgHeight;
            // scale as needed
            tx.scale(scaleRatio, scaleRatio);
        } else {// we don't need any transform here, just save it to file and return
            outputStream.write(srcByte);
            return;
        }

        // create thumbnail image
        BufferedImage bufferedImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bufferedImage.createGraphics();
        boolean useTransform = false;
        if (useTransform) {// use transfrom to draw
            //log.trace("use transform");
            g.drawImage(srcImage, tx, null);
        } else {// use java filter
            //log.trace("use filter");
            Image scaleImage = getScaledInstance(srcImage, imgWidth, imgHeight);
            g.drawImage(scaleImage, 0, 0, null);
        }
        g.dispose();// free resource
        // write it to outputStream 
        // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
        // encoder.encode(bufferedImage);

        ImageIO.write(bufferedImage, "jpeg", outputStream);
    } catch (IOException e) {
        log.error("Error", e);
        throw e;
    } finally {// this finally is very important
        try {
            inputStream.close();
        } catch (IOException e) {
            /* ignore */
            e.printStackTrace();
        }
        try {
            outputStream.close();
        } catch (IOException e) {/* ignore */
            e.printStackTrace();
        }
    }
}

From source file:cpcc.ros.sim.osm.Camera.java

/**
 * @return the extracted image.//from  w ww . j  a  v a 2s. co  m
 * @throws IOException thrown in case of errors.
 */
private byte[] extractImage() throws IOException {
    double dTilesX = bottomRightTile.getxTile() - topLeftTile.getxTile();
    double dTilesY = bottomRightTile.getyTile() - topLeftTile.getyTile();

    int height = (int) (dTilesY * cfg.getTileHeight()) + bottomRightTile.getyPixel() - topLeftTile.getyPixel();
    int width = (int) (dTilesX * cfg.getTileWidth()) + bottomRightTile.getxPixel() - topLeftTile.getxPixel();

    if (height < 1) {
        height = 1;
    }

    if (width < 1) {
        width = 1;
    }

    BufferedImage image = map.getSubimage(topLeftTile.getxPixel(), topLeftTile.getyPixel(), width, height);
    Image scaledImage = image.getScaledInstance(cfg.getCameraWidth(), cfg.getCameraHeight(), 0);

    BufferedImage cameraImage = new BufferedImage(cfg.getCameraWidth(), cfg.getCameraHeight(),
            BufferedImage.TYPE_INT_RGB);
    cameraImage.createGraphics().drawImage(scaledImage, 0, 0, null);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ImageIO.write(cameraImage, "PNG", bos);

    return bos.toByteArray();
}

From source file:de.anycook.upload.UploadHandler.java

/**
 * speichert eine grosse Version des Bildes
 *
 * @param image    BufferedImage/*from   w w  w . j  av a 2  s.  c  o m*/
 * @param filename Name der zu erzeugenden Datei
 */
private void saveOriginalImage(BufferedImage image, String filename) throws IOException {
    int height = image.getHeight();
    int width = image.getWidth();

    BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    newImage.getGraphics().drawImage(image, 0, 0, null);

    imageSaver.save("original/", filename, newImage);

}

From source file:it.lilik.capturemjpeg.CaptureMJPEG.java

/**
 * Creates a <code>CaptureMJPEG</code> with HTTP Auth credential
 * /*w  w w  .  ja va  2  s  .  c  om*/
 * @param parent the <code>ImageWindow</code> which uses this object
 * @param url the MJPEG stream URI
 * @param username HTTP AUTH username
 * @param password HTTP AUTH password
 */
public CaptureMJPEG(VideoPanel parent, String url, String username, String password) {
    this.lastImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    //this.lastImage.init(parent.width, parent.height, PImage.RGB);
    this.method = new GetMethod(url);
    this.shouldStop = false;
    this.changeImageSize = false;
    buffer = new CircularBuffer();
    // create a singular HttpClient object
    this.client = new HttpClient();

    // establish a connection within 5 seconds
    this.client.getHttpConnectionManager().getParams().setConnectionTimeout(HTTP_TIMEOUT);

    if (username != null && password != null) {
        this.setCredential(username, password);
    }
    setURL(url);
    //set the ThreadName useful for debug
    setName("CaptureMJPEG");
    setPriority(Thread.MAX_PRIORITY);

    this.parent = parent;

    //System.out.println("Capture initialized");

    //parent.registerDispose(this);       
    //register callback
    try {
        captureEventMethod = parent.getClass().getMethod("captureMJPEGEvent", new Class[] { Image.class });
    } catch (Exception e) {
        System.out.println("Cannot set callback " + e.getMessage());
    }
}