Exemplo n.º 1
0
  // Takes a PImage and compresses it into a JPEG byte stream
  // Adapted from Dan Shiffman's UDP Sender code
  public byte[] compressImage(PImage img) {
    // We need a buffered image to do the JPG encoding
    BufferedImage bimg = new BufferedImage(img.width, img.height, BufferedImage.TYPE_INT_RGB);

    img.loadPixels();
    bimg.setRGB(0, 0, img.width, img.height, img.pixels, 0, img.width);

    // Need these output streams to get image as bytes for UDP communication
    ByteArrayOutputStream baStream = new ByteArrayOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(baStream);

    // Turn the BufferedImage into a JPG and put it in the BufferedOutputStream
    // Requires try/catch
    try {
      ImageIO.write(bimg, "jpg", bos);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Get the byte array, which we will send out via UDP!
    return baStream.toByteArray();
  }
 private void writeToFile(File selectedFile, ImageWriterSpiFileFilter ff) {
   try {
     ImageOutputStream ios = ImageIO.createImageOutputStream(selectedFile);
     ImageWriter iw = ff.getImageWriterSpi().createWriterInstance();
     iw.setOutput(ios);
     ImageWriteParam iwp = iw.getDefaultWriteParam();
     if (iwp.canWriteCompressed()) {
       iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
       // set maximum image quality
       iwp.setCompressionQuality(1.f);
     }
     Image image = viewerPanel.getImage();
     BufferedImage bufferedImage;
     if (viewerPanel.getImage() instanceof BufferedImage)
       bufferedImage = (BufferedImage) viewerPanel.getImage();
     else {
       bufferedImage =
           new BufferedImage(
               image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
       bufferedImage.createGraphics().drawImage(image, 0, 0, null);
     }
     iw.write(null, new IIOImage(bufferedImage, null, null), iwp);
     iw.dispose();
     ios.close();
   } catch (IOException ioe) {
     JOptionPane.showMessageDialog(
         viewerPanel,
         messagesBundle.getString(
             "ImageViewerPanelSaveAction." + "Error_during_image_saving_message_7"),
         //$NON-NLS-1$
         messagesBundle.getString("ImageViewerPanelSaveAction." + "Error_dialog_title_8"),
         //$NON-NLS-1$
         JOptionPane.ERROR_MESSAGE);
     ioe.printStackTrace();
   }
 }