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:org.wkm.mtool.service.QRCodeService.java

/**
 * ??(QRCode)//  ww w .ja v a 2s .  c  om
 * @param content
 * @param imgFile
 */
private void encoderQRCode(String content, File imgFile) {
    try {
        Qrcode qrcodeHandler = new Qrcode();
        qrcodeHandler.setQrcodeErrorCorrect('M');
        qrcodeHandler.setQrcodeEncodeMode('B');
        qrcodeHandler.setQrcodeVersion(7);

        System.out.println(content);
        byte[] contentBytes = content.getBytes(Consts.UTF_8.name());

        BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB);

        Graphics2D gs = bufImg.createGraphics();

        gs.setBackground(Color.WHITE);
        gs.clearRect(0, 0, 140, 140);

        // ? > BLACK
        gs.setColor(Color.BLACK);

        // ??? ???
        int pixoff = 2;
        //  > ?
        if (contentBytes.length > 0 && contentBytes.length < 120) {
            boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
            for (int i = 0; i < codeOut.length; i++) {
                for (int j = 0; j < codeOut.length; j++) {
                    if (codeOut[j][i]) {
                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                    }
                }
            }
        } else {
            System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. ");
        }

        gs.dispose();
        bufImg.flush();

        // ??QRCode
        ImageIO.write(bufImg, "png", imgFile);

    } catch (Exception e) {
        log.info("Exception:" + e.getMessage());
    }
}

From source file:doge.photo.DogePhotoManipulator.java

@Override
public Photo manipulate(Photo photo) throws IOException {
    BufferedImage sourceImage = readImage(photo);
    BufferedImage destinationImage = manipulate(sourceImage);
    Photo resultPhoto = () -> {/*w  ww.  j a  v  a  2  s  .c  om*/
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.85f);
        writer.setOutput(ios);
        writer.write(null, new IIOImage(destinationImage, null, null), param);
        ImageIO.write(destinationImage, "jpeg", outputStream);
        return new ByteArrayInputStream(outputStream.toByteArray());
    };
    return resultPhoto;
}

From source file:org.lightadmin.core.web.util.ImageResourceControllerSupport.java

private ResponseEntity<?> scaledImageResourceResponse(byte[] bytes, int width, int height, MediaType mediaType)
        throws IOException {
    BufferedImage sourceImage = read(new ByteArrayInputStream(bytes));
    BufferedImage image = resizeImage(sourceImage, width, height);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    ImageIO.write(image, mediaType.getSubtype(), byteArrayOutputStream);

    return imageResourceResponse(byteArrayOutputStream.toByteArray(), mediaType);
}

From source file:com.synnex.saas.platform.core.servlet.CaptchaServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from ww  w  . jav a2  s  .c  o  m*/
        int width = 50;
        int height = 18;
        String captchaCode = RandomStringUtils.random(4, true, true);
        HttpSession session = request.getSession(true);
        session.setAttribute("captchaCode", captchaCode);

        response.setContentType("images/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        ServletOutputStream out = response.getOutputStream();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        Font mFont = new Font("Times New Roman", Font.BOLD, 18);
        g.setFont(mFont);
        g.setColor(getRandColor(160, 200));
        Random random = new Random();
        for (int i = 0; i < 155; i++) {
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            int x3 = random.nextInt(12);
            int y3 = random.nextInt(12);
            g.drawLine(x2, y2, x2 + x3, y2 + y3);
        }
        g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        g.drawString(captchaCode, 2, 16);
        g.dispose();
        ImageIO.write((BufferedImage) image, "JPEG", out);
        out.close();
    } catch (Exception e) {
        logger.error("Generate captcha failed.", e);
    }
}

From source file:de.uni_siegen.wineme.come_in.thumbnailer.thumbnailers.PDFBoxThumbnailer.java

@Override
public void generateThumbnail(final File input, final File output) throws IOException, ThumbnailerException {

    FileUtils.deleteQuietly(output);/*from w ww .j a  va 2s .c o  m*/

    PDDocument document = null;
    try {
        try {
            document = PDDocument.load(input);
        } catch (final IOException e) {
            throw new ThumbnailerException("Could not load PDF File", e);
        }

        final List<?> pages = document.getDocumentCatalog().getAllPages();
        final PDPage page = (PDPage) pages.get(0);
        final BufferedImage tmpImage = this.writeImageForPage(document, page, BufferedImage.TYPE_INT_RGB);

        if (tmpImage.getWidth() == this.thumbWidth) {
            ImageIO.write(tmpImage, PDFBoxThumbnailer.OUTPUT_FORMAT, output);
        } else {
            final ResizeImage resizer = new ResizeImage(this.thumbWidth, this.thumbHeight);
            resizer.resizeMethod = ResizeImage.NO_RESIZE_ONLY_CROP;
            resizer.setInputImage(tmpImage);
            resizer.writeOutput(output);
        }
    }

    finally {
        if (document != null) {
            try {
                document.close();
            } catch (final IOException e) {
            }
        }
    }
}

From source file:com.github.orangefoundry.gorender.controllers.ImageRenderController.java

private byte[] renderPlaceHolder(String size, String colour) throws IOException {

    if (size == null || size.isEmpty()) {
        size = Default.SIZE.getValue();/*from ww w. j  a va 2s .  c  om*/
    }

    if (colour == null || colour.isEmpty()) {
        colour = Default.COLOUR.getValue();
    }

    String[] sizes = new String[2];

    if (size != null && !size.isEmpty()) {
        sizes = size.toLowerCase().split("x");
    }

    int width = Integer.parseInt(sizes[0]), height = Integer.parseInt(sizes[1]);

    final ColourToAWTColour colourToAWTColour = new ColourToAWTColour();
    Color myColour = colourToAWTColour.getColour(colour);
    int rgb = myColour.getRGB();

    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    int[] data = new int[width * height];
    int i = 0;
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            data[i++] = rgb;
        }
    }
    bi.setRGB(0, 0, width, height, data, 0, width);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();

    ImageIO.write(bi, "png", bao);

    return bao.toByteArray();
}

From source file:jp.canetrash.maven.plugin.bijint.BujintMojo.java

/**
 * @param image//from   ww w  . j a v  a2s . co m
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws UnsupportedEncodingException
 */
private String getAsciiArt(BufferedImage image)
        throws IOException, ClientProtocolException, UnsupportedEncodingException {
    File tmpfile = File.createTempFile("bjint_", ".jpg");
    ImageIO.write(image, "jpg", tmpfile);

    // http://picascii.com/????
    // ?????
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("http://picascii.com/");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    entity.consumeContent();

    // ???
    HttpPost httppost = new HttpPost("http://picascii.com/upload.php");
    //HttpPost httppost = buildDefaultHttpMessage(new HttpPost("http://localhost:8080/sa-struts-tutorial/upload/"));

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    FileBody bin = new FileBody(tmpfile, "image/jpeg");
    reqEntity.addPart("imageupload", bin);
    reqEntity.addPart("MAX_FILE_SIZE", new StringBody("1000000"));
    reqEntity.addPart("url", new StringBody(""));
    reqEntity.addPart("quality", new StringBody("3"));
    reqEntity.addPart("size", new StringBody("1"));

    httppost.setEntity(reqEntity);

    response = httpclient.execute(httppost);
    String responseHtml = IOUtils.toString(response.getEntity().getContent());

    httpclient.getConnectionManager().shutdown();

    // tmpFile?
    tmpfile.delete();
    return bringOutAsciiArtString(responseHtml);
}

From source file:com.springsecurity.plugin.util.ImageResizer.java

public File reziseTo(File source, File dest, int width, int height, String ext) {
    try {//from   w  ww . ja v  a2s  . c o m
        ImageResizer img = new ImageResizer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img.scale(source, width, height), ext, baos);
        dest.delete();
        baos.writeTo(new FileOutputStream(dest));
        baos.flush();
    } catch (IOException e) {
        System.err.println("err" + e.getMessage());
    }
    return dest;
}

From source file:com.aistor.common.servlet.ValidateCodeServlet.java

private void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    /*/* w  ww  .j a  v a 2 s .c o  m*/
     * ??
     */
    String width = request.getParameter("width");
    String height = request.getParameter("height");
    if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
        w = NumberUtils.toInt(width);
        h = NumberUtils.toInt(height);
    }

    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    /*
     * ?
     */
    createBackground(g);

    /*
     * ?
     */
    String s = createCharacter(g);
    request.getSession().setAttribute("validateCode", s);

    g.dispose();
    OutputStream out = response.getOutputStream();
    ImageIO.write(image, "JPEG", out);
    out.close();

}

From source file:davmail.util.IOUtil.java

/**
 * Resize image bytes to a max width or height image size.
 *
 * @param inputBytes input image bytes//from   w w  w .j a  v  a 2  s . com
 * @param max        max size
 * @return scaled image bytes
 * @throws IOException on error
 */
public static byte[] resizeImage(byte[] inputBytes, int max) throws IOException {
    BufferedImage inputImage = ImageIO.read(new ByteArrayInputStream(inputBytes));
    if (inputImage == null) {
        throw new IOException("Unable to decode image data");
    }
    BufferedImage outputImage = resizeImage(inputImage, max);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(outputImage, "jpg", baos);
    return baos.toByteArray();
}