Example usage for javax.imageio ImageIO write

List of usage examples for javax.imageio ImageIO write

Introduction

In this page you can find the example usage for javax.imageio ImageIO write.

Prototype

public static boolean write(RenderedImage im, String formatName, OutputStream output) throws IOException 

Source Link

Document

Writes an image using an arbitrary ImageWriter that supports the given format to an OutputStream .

Usage

From source file:com.seleniumtests.util.imaging.ImageProcessor.java

public static String toBase64(BufferedImage img) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    OutputStream b64 = new Base64.OutputStream(os);
    ImageIO.write(img, "png", b64);
    return os.toString("UTF-8");
}

From source file:com.octo.captcha.module.web.image.ImageToJpegHelper.java

/**
 * retrieve a new ImageCaptcha using ImageCaptchaService and flush it to the response.<br/> Captcha are localized
 * using request locale.<br/>// ww w. j  a  va2 s.c o m
 * <p/>
 * This method returns a 404 to the client instead of the image if the request isn't correct (missing parameters,
 * etc...)..<br/> The log may be null.<br/>
 *
 * @param theRequest  the request
 * @param theResponse the response
 * @param log         a commons logger
 * @param service     an ImageCaptchaService instance
 *
 * @throws java.io.IOException if a problem occurs during the jpeg generation process
 */
public static void flushNewCaptchaToResponse(HttpServletRequest theRequest, HttpServletResponse theResponse,
        Log log, ImageCaptchaService service, String id, Locale locale) throws IOException {

    // call the ImageCaptchaService method to retrieve a captcha
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {
        BufferedImage challenge = service.getImageChallengeForID(id, locale);
        // the output stream to render the captcha image as jpeg into

        ImageIO.write(challenge, "jpg", jpegOutputStream);

    } catch (IllegalArgumentException e) {
        //    log a security warning and return a 404...
        if (log != null && log.isWarnEnabled()) {
            log.warn("There was a try from " + theRequest.getRemoteAddr()
                    + " to render an captcha with invalid ID :'" + id + "' or with a too long one");
            theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    theResponse.setHeader("Cache-Control", "no-store");
    theResponse.setHeader("Pragma", "no-cache");
    theResponse.setDateHeader("Expires", 0);

    theResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = theResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
}

From source file:ImageUtil.java

public static ByteArrayOutputStream fit(ByteArrayInputStream bais, int width, int height) throws IOException {
    BufferedImage src = ImageIO.read(bais);
    int newWidth;
    int newHeight;

    Float scale;/*  w w  w  .jav  a  2s  .c  o  m*/
    if (src.getWidth() > src.getHeight()) {
        scale = Float.valueOf(width) / Float.valueOf(src.getWidth());
    } else {
        scale = Float.valueOf(height) / Float.valueOf(src.getHeight());
    }

    newWidth = Float.valueOf(src.getWidth() * scale).intValue();
    newHeight = Float.valueOf(src.getHeight() * scale).intValue();

    // System.out.println("--- " + src.getWidth() + " - " + width);
    // System.out.println("--- " + src.getHeight() + " - " + height);
    // System.out.println("--- " + scale + " -- " + Float.valueOf(src.getWidth() * scale).intValue() + " -- " + Float.valueOf(src.getHeight() * scale).intValue());

    BufferedImage temp = scale(src, newWidth, newHeight);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(temp, "JPG", baos);

    return baos;
}

From source file:com.daniel.processimage.ImageManager.java

public byte[] readImage(Part file) throws FileNotFoundException, IOException {
    InputStream is = file.getInputStream();
    BufferedImage bufferedImage = ImageIO.read(is);
    ByteArrayOutputStream byteMas = new ByteArrayOutputStream();
    ImageIO.write(bufferedImage, "png", byteMas);
    byteMas.flush();//ww  w .  j a v  a  2s. c o m
    byte[] imageInBytes = byteMas.toByteArray();
    byteMas.close();

    return imageInBytes;
}

From source file:javafx1.Testpics.java

private void bildSchleife() {
    File f = new File("F:/NetBeansProjekte/pictures");
    File[] fileArray = f.listFiles();
    java.util.Arrays.sort(fileArray);
    for (File file : fileArray) {
        try {//  w w  w  .  j av  a2  s  .c om
            System.out.println("file: " + file.getCanonicalPath());
            File outputfile = new File(file.getCanonicalPath() + ".jpg");
            BufferedImage bi = ImageIO.read(file);
            System.out.println(" enc" + encodeToString(bi, "jpg"));
            ImageIO.write(bi, "jpg", outputfile);
            bi = ImageIO.read(outputfile);
            System.out.println(" w" + bi.getWidth() + " h" + bi.getHeight());
            byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
            // System.out.println(new String(data));
            byte[] x = Base64.encodeBase64URLSafe(data);
            System.out.println("x" + new String(x));
            String b64 = Base64.encodeBase64String(data);
            System.out.println("64" + b64);

            //                byte[] backToBytes = Base64.decodeBase64(base64String);
            //                InputStream in = new ByteArrayInputStream(backToBytes);
            //                BufferedImage bi;
            //                bi = ImageIO.read(in);
            //byte[] xx = base64String.getBytes(StandardCharsets.UTF_8);
            // bild, wie es von http kommt
            //                RunPic rp = new RunPic(this, data);
            //                Platform.runLater(rp);
            try {
                Thread.sleep(50);
                break;
            } catch (InterruptedException ex) {
                Logger.getLogger(JavaFX1.class.getName()).log(Level.SEVERE, null, ex);
            }

        } catch (IOException ex) {
            Logger.getLogger(JavaFX1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:ChartServlet.java

/** Draw a Graphical Chart in response to a user request */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setContentType("image/jpeg");

    // Create an Image
    BufferedImage img = new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);

    // Get the Image's Graphics, and draw.
    Graphics2D g = img.createGraphics();

    // In real life this would call some charting software...
    g.setColor(Color.white);//from   w  ww .  j  ava2 s  .com
    g.fillRect(0, 0, W, H);
    g.setColor(Color.green);
    g.fillOval(100, 75, 50, 50);

    // Write the output
    OutputStream os = response.getOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(os);

    if (!ImageIO.write(img, "jpeg", ios)) {
        log("Boo hoo, failed to write JPEG");
    }
    ios.close();
    os.close();
}

From source file:DBMS.UpdateFileUpload.java

public static boolean processFile(String path, FileItemStream item, int id) {
    try {/*from w  ww .  ja  v  a 2  s  .c om*/
        String check = item.getName();
        if (check.endsWith(".jpg") || check.endsWith(".JPG")) {
            String imstring = "images/" + Integer.toString(id);
            File f = new File(path + File.separator + imstring);
            if (!f.exists())
                f.mkdir();
            File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
            FileOutputStream fos = new FileOutputStream(savedFile);
            InputStream is = item.openStream();
            int x = 0;
            byte[] b = new byte[1024];
            while ((x = is.read(b)) != -1) {
                fos.write(b, 0, x);
            }
            fos.flush();
            fos.close();
            String dbimage = imstring + "/a.jpg";
            //dc.enterImage(dbimage);
            //im =dbimage;
            //System.out.println("Resizing!");
            //Resize rz = new Resize();
            //rz.resize(dbimage);
            BufferedImage originalImage = ImageIO.read(savedFile);
            int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
            BufferedImage resizeImageJpg = resizeImage(originalImage, type);
            ImageIO.write(resizeImageJpg, "jpg", savedFile);
            File rFile = new File(f.getAbsolutePath() + "/a.jpg");
            savedFile.renameTo(rFile);
            ProfileEditDB dc = new ProfileEditDB();
            dc.enterImage(id, dbimage);
            System.out.println("Link Entered to Database!");
            return true;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:net.dv8tion.jda.utils.AvatarUtil.java

public static Avatar getAvatar(BufferedImage img) {
    try {//from w  w w.j a va 2 s . com
        //resizing
        img = resize(img);
        //writing + converting to jpg if necessary
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", bout);
        bout.close();

        return new Avatar("data:image/jpeg;base64,"
                + StringUtils.newStringUtf8(Base64.getEncoder().encode(bout.toByteArray())));
    } catch (IOException e) {
        JDAImpl.LOG.log(e);
    }
    return null;
}

From source file:com.eviware.loadui.ui.fx.util.NodeUtils.java

public static String toBase64Image(BufferedImage bimg) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//from   w ww  . j  a v  a2  s  .  c om
        ImageIO.write(bimg, "png", baos);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new Base64().encodeToString(baos.toByteArray());
}

From source file:QRCode.java

public static String createQRCode(String arg) {
    int size = 125;
    String fileType = "png";
    File myFile = null;//from  www  .  j  a  v a  2 s .  c  o  m
    UUID uuid = UUID.nameUUIDFromBytes(arg.getBytes());

    try {
        myFile = File.createTempFile("temp-file-name", ".png");

        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix byteMatrix = qrCodeWriter.encode(uuid.toString(), 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);
                }
            }
        }
        ImageIO.write(image, fileType, myFile);
        //System.out.println("\n\nYou have successfully created QR Code " + myFile.getCanonicalPath());
        return myFile.getCanonicalPath();
    } catch (WriterException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}