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:emily.command.fun.RedditCommand.java

@Override
public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author,
        Message inputMessage) {//from  w  ww .  j av a2  s  .c om
    String subReddit = "funny";
    if (args.length > 0) {
        subReddit = args[0];
    }
    List<Post> dailyTop = RedditScraper.getDailyTop(subReddit);
    if (dailyTop.size() == 0) {
        return Templates.command.reddit_sub_not_found.formatGuild(channel);
    }
    Random rng = new Random();
    Post post;
    do {
        int index = rng.nextInt(dailyTop.size());
        post = dailyTop.remove(index);
        if (post.data.is_self) {
            break;
        }
        if (whitelistedDomains.contains(post.data.domain)) {
            break;
        }
    } while (dailyTop.size() > 0);
    if (post.data.is_self) {
        return ":newspaper:\n" + post.data.getTitle() + "\n" + post.data.getSelftext();
    }
    if (post.data.url != null && post.data.url.length() > 20) {
        return post.data.title + "\n" + post.data.url;
    }
    ImagePreview preview = post.data.getPreview();
    if (preview != null && preview.images.size() > 0) {
        if (channel.getType().equals(ChannelType.TEXT) && !PermissionUtil.checkPermission((TextChannel) channel,
                ((TextChannel) channel).getGuild().getSelfMember(), Permission.MESSAGE_ATTACH_FILES)) {
            return Templates.permission_missing.formatGuild(channel, "MESSAGE_ATTACH_FILES");
        }
        for (Image image : preview.images) {
            try (InputStream in = new URL(StringEscapeUtils.unescapeHtml4(image.source.url)).openStream()) {
                File outputfile = new File("tmp_" + channel.getId() + ".jpg");
                ImageIO.write(ImageIO.read(in), "jpg", outputfile);
                bot.queue.add(
                        channel.sendFile(outputfile, new MessageBuilder().append(post.data.title).build()),
                        message -> outputfile.delete());
                return "";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return Templates.command.reddit_nothing.formatGuild(channel);
}

From source file:com.liud.dailynote.ThumbnailatorTest.java

private void testYS8() throws IOException {
    String result = "src/main/resources/images/";
    OutputStream os = new FileOutputStream(result + "sijili_out.jpg");

    Image image = ImageIO.read(new File(result + "sijili.jpg"));

    BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    bufferedImage.getGraphics().drawImage(image.getScaledInstance(100, 100, image.SCALE_SMOOTH), 0, 0, null);

    ImageIO.write(bufferedImage, "jpg", os);
    os.close();//from  www . j a va  2s .  c o m
}

From source file:com.kahlon.guard.controller.PersonImageManager.java

/**
 * Upload person image file/*from   www. j  a  v a 2 s .  co m*/
 *
 * @param event
 * @throws java.io.IOException
 */
public void onUpload(FileUploadEvent event) throws IOException {
    photo = getRandomImageName();
    byte[] data = IOUtils.toByteArray(event.getFile().getInputstream());

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator
            + "image" + File.separator + "temp" + File.separator + photo + ".png";
    if (fileNames == null) {
        fileNames = new ArrayList<>();
    }
    fileNames.add(newFileName);

    FileImageOutputStream imageOutput;
    try {
        imageOutput = new FileImageOutputStream(new File(newFileName));
        imageOutput.write(data, 0, data.length);
        imageOutput.close();

        BufferedImage originalImage = ImageIO.read(new File(newFileName));
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

        BufferedImage resizeImagePng = resizeImageWithHint(originalImage, type);
        ImageIO.write(resizeImagePng, "png", new File(newFileName));

    } catch (Exception e) {
        throw new FacesException("Error in writing captured image.");
    }
    FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);
    imageUpload = false;
}

From source file:com.seleniumtests.util.FileUtility.java

/**
 * Constructs ImageElement from bytes and stores it.
 *
 * @param  path/* w  w  w  . j  a  v a2 s. c  o  m*/
 */
public static synchronized void writeImage(final String path, BufferedImage bufImage) {
    if (bufImage == null) {
        return;
    }

    File parentDir = new File(path).getParentFile();
    if (!parentDir.exists()) {
        parentDir.mkdirs();
    }

    try (FileOutputStream fos = new FileOutputStream(path)) {

        ImageIO.write(bufImage, "png", fos);
    } catch (Exception e) {
        logger.warn(e);
    }
}

From source file:nu.yona.server.subscriptions.rest.UserPhotoController.java

private static byte[] getPngBytes(MultipartFile file) {
    try (InputStream inStream = file.getInputStream()) {
        BufferedImage image = ImageIO.read(inStream);
        if (image == null) {
            throw InvalidDataException.unsupportedPhotoFileType();
        }//  w  w  w.jav a 2 s .  c o m
        ByteArrayOutputStream pngBytes = new ByteArrayOutputStream();
        ImageIO.write(image, "png", pngBytes);
        return pngBytes.toByteArray();
    } catch (IOException e) {
        throw YonaException.unexpected(e);
    }
}

From source file:com.illustrationfinder.IllustrationFinderController.java

@RequestMapping(value = "/", method = RequestMethod.GET, params = { "url", "preferred-width",
        "preferred-height" })
public ModelAndView showIllustrationFinderResults(ModelMap modelMap, @RequestParam(value = "url") String pUrl,
        @RequestParam(value = "preferred-width") String pPreferredWidth,
        @RequestParam(value = "preferred-height") String pPreferredHeight) {
    final ModelAndView modelAndView = new ModelAndView("/IllustrationFinderView");

    // Add the URL to attributes
    modelMap.addAttribute("pUrl", pUrl);

    // Check if the URL is valid
    boolean isUrlValid = false;

    String url = pUrl;//ww w  .  ja  v a 2 s . c  om
    if (url != null) {
        url = StringEscapeUtils.escapeHtml4(url);

        if (new UrlValidator(new String[] { "http", "https" }).isValid(url)) {
            isUrlValid = true;
        }
    }

    modelMap.addAttribute("isUrlValid", isUrlValid);

    // Get the images
    try {
        if (isUrlValid) {
            final IPostProcessor postProcessor = new HtmlPostProcessor();
            final GoogleSearchEngine searchEngine = new GoogleSearchEngine();
            final IImageProcessor<BufferedImage, BufferedImageOp> imageProcessor = new BufferedImageProcessor();

            imageProcessor.setPreferredSize(
                    new Dimension(Integer.parseInt(pPreferredWidth), Integer.parseInt(pPreferredHeight)));

            final IllustrationFinder illustrationFinder = new IllustrationFinder();
            illustrationFinder.setPostProcessor(postProcessor);
            illustrationFinder.setSearchEngine(searchEngine);
            illustrationFinder.setImageProcessor(imageProcessor);

            final List<BufferedImage> images = illustrationFinder.getImages(new URL(pUrl));

            // Convert images to base64 strings
            final List<String> imagesAsStrings = new ArrayList<>();

            if (images != null) {
                for (BufferedImage image : images) {
                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        ImageIO.write(image, "png", baos);
                        baos.flush();
                        final byte[] imageInByteArray = baos.toByteArray();
                        baos.close();
                        final String b64 = DatatypeConverter.printBase64Binary(imageInByteArray);

                        imagesAsStrings.add(b64);
                    } catch (IOException e) {
                        // Failed to convert the image
                    }
                }
            }

            modelMap.addAttribute("images", imagesAsStrings);
        }
    } catch (IOException e) {
        // Exception triggered if the URL is malformed, it should not happen because the URL is validated before
    }

    return modelAndView;
}

From source file:bq.jpa.demo.datetype.service.EmployeeService.java

private byte[] readImage(String fileName) throws IOException {
    BufferedImage pngfile = ImageIO.read(getClass().getResourceAsStream(fileName));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(pngfile, "png", baos);
    baos.flush();/*  w w w . j a v a 2 s .c  o m*/
    return baos.toByteArray();
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static String getBase64Data(BufferedImage buffImage, String formatName, Node node) throws Exception {
    int numBytes = buffImage.getWidth() * buffImage.getHeight() * 4;
    ByteArrayOutputStream baos = new ByteArrayOutputStream(numBytes);
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    boolean status = ImageIO.write(buffImage, formatName, ios);
    if (!status) {
        throw new Exception("No suitable ImageIO writer found by ImageParser.getBase64Data() for image format "
                + formatName);/*from  w w w  .  j a v a 2s.c o m*/
    }
    byte[] imageData = baos.toByteArray();
    // String base64String = Base64.encodeBase64String(imageData); this is
    // unchunked (no line breaks) which is unwieldy
    byte[] base64Data = Base64.encodeBase64Chunked(imageData);
    // 2011-11-15 PwD uncomment for Java 1.7 String base64String = new
    // String(base64Data, StandardCharsets.UTF_8);
    String base64String = new String(base64Data, "UTF-8"); // 2011-11-15 PwD
                                                           // for Java 1.6;
                                                           // remove for
                                                           // Java 1.7
    return base64String;
}

From source file:com.l1j5.web.common.utils.ImageUtils.java

public static void getImageThumbnail(BufferedInputStream stream_file, String save, String type, int w) {

    try {//  www .j a  va2  s.c o  m
        File file = new File(save);
        BufferedImage bi = ImageIO.read(stream_file);

        int width = bi.getWidth();
        int height = bi.getHeight();

        double ratio = (double) height / width;
        height = (int) (w * ratio);
        if (w < width) {
            width = w;
        }

        BufferedImage bufferIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Image atemp = bi.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);

        Graphics2D g2 = bufferIm.createGraphics();
        g2.drawImage(atemp, 0, 0, width, height, null);
        ImageIO.write(bufferIm, type, file);
    } catch (Exception e) {
        log.error(e);
    }

}

From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java

/**
 * Scale an image and return the dimensions (width and height) as int array
 *
 * @param original  original file//w w  w . jav a 2  s.co m
 * @param scaled    scaled file
 * @param extension extension
 * @param width     desired width
 * @param height    desired height
 * @return actual width ([0]) and height ([1]) of scaled image
 * @throws FxApplicationException on errors
 */
public static int[] scale(File original, File scaled, String extension, int width, int height)
        throws FxApplicationException {
    if (HEADLESS && FxMediaImageMagickEngine.IM_AVAILABLE && ".GIF".equals(extension)) {
        //native headless engine can't handle gif transparency ... so if we have IM we use it, else
        //transparent pixels will be black
        return FxMediaImageMagickEngine.scale(original, scaled, extension, width, height);
    }
    BufferedImage bi;
    try {
        bi = ImageIO.read(original);
    } catch (Exception e) {
        LOG.info("Failed to read " + original.getName() + " using ImageIO, trying sanselan");
        try {
            bi = Sanselan.getBufferedImage(original);
        } catch (Exception e1) {
            throw new FxApplicationException(LOG, "ex.media.readFallback.error", original.getName(), extension,
                    e.getMessage(), e1.getMessage());
        }
    }
    BufferedImage bi2 = scale(bi, width, height);

    String eMsg;
    boolean fallback;
    try {
        fallback = !ImageIO.write(bi2, extension.substring(1), scaled);
        eMsg = "No ImageIO writer found.";
    } catch (Exception e) {
        eMsg = e.getMessage();
        fallback = true;
    }
    if (fallback) {
        try {
            Sanselan.writeImage(bi2, scaled, getImageFormatByExtension(extension), new HashMap());
        } catch (Exception e1) {
            throw new FxApplicationException(LOG, "ex.media.write.error", scaled.getName(), extension,
                    eMsg + ", " + e1.getMessage());
        }
    }
    return new int[] { bi2.getWidth(), bi2.getHeight() };
}