示例#1
0
  private void jButton3ActionPerformed(
      final ActionEvent evt) { // GEN-FIRST:event_jButton3ActionPerformed

    try {
      BufferedImage image = (BufferedImage) guiMap2D.getCanvas().getSnapShot();
      Object output0 = new File("temp0.png");
      Object output1 = new File("temp1.png");

      final Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType("image/png");
      while (writers.hasNext()) {
        final ImageWriter writer = writers.next();
        final ImageWriterSpi spi = writer.getOriginatingProvider();
        if (spi.canEncodeImage(image)) {
          ImageOutputStream stream = null;
          if (!isValidType(spi.getOutputTypes(), output0)) {
            stream = ImageIO.createImageOutputStream(output0);
            output0 = stream;
            stream = ImageIO.createImageOutputStream(output1);
            output1 = stream;
          }

          ImageWriteParam iwp = writer.getDefaultWriteParam();
          iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
          iwp.setCompressionQuality(0);
          IIOImage iimage = new IIOImage(image, null, null);
          writer.setOutput(output0);
          writer.write(null, iimage, iwp);
          writer.dispose();

          iwp = writer.getDefaultWriteParam();
          iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
          iwp.setCompressionQuality(1);
          iimage = new IIOImage(image, null, null);
          writer.setOutput(output1);
          writer.write(null, iimage, iwp);
          writer.dispose();

          if (output0 != null) {
            ((ImageOutputStream) output0).close();
            ((ImageOutputStream) output1).close();
          }

          return;
        }
      }
    } catch (Exception rx) {
      rx.printStackTrace();
    }
  } // GEN-LAST:event_jButton3ActionPerformed
  @Test
  public void lossyWrite() throws Exception {
    File f = File.createTempFile("test-jpeg2000-lossy", ".jp2");
    f.deleteOnExit();
    Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jp2");
    assertTrue(writers.hasNext());
    ImageWriter writer = writers.next();
    J2KImageWriteParam writeParams = (J2KImageWriteParam) writer.getDefaultWriteParam();
    writeParams.setLossless(false);
    writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    writeParams.setCompressionType("JPEG2000");
    //        writeParams.setFilter(J2KImageWriteParam.FILTER_97);

    writeParams.setCompressionQuality(0.0f);
    writeParams.setEncodingRate(0.5f);
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(image, null, null), writeParams);
    writer.dispose();
    ios.close();
    assertTrue("Expected file size < 1MB", f.length() < 128 * 1024);
    // System.out.println(f.length());
    BufferedImage read = ImageIO.read(f);
    assertEquals(SIZE, read.getWidth());
  }
示例#3
0
  /**
   * Compress and save an image to the disk. Currently this method only supports JPEG images.
   *
   * @param image The image to save
   * @param toFileName The filename to use
   * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images, or
   *     <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
   */
  public static void saveCompressedImage(BufferedImage image, String toFileName, int type) {
    try {
      if (type == IMAGE_PNG) {
        throw new UnsupportedOperationException("PNG compression not implemented");
      }

      Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer;
      writer = (ImageWriter) iter.next();

      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
      writer.setOutput(ios);

      ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());

      iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      iwparam.setCompressionQuality(0.7F);

      writer.write(null, new IIOImage(image, null, null), iwparam);

      ios.flush();
      writer.dispose();
      ios.close();
    } catch (IOException e) {
      throw new ForumException(e);
    }
  }
示例#4
0
  /**
   * 图片文件转换为tif格式
   *
   * @param imageFile 文件路径
   * @param imageFormat 文件扩展名
   * @return
   */
  public static File createImage(File imageFile, String imageFormat) {
    File tempFile = null;
    try {
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
      ImageReader reader = readers.next();

      ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);
      // Read the stream metadata
      IIOMetadata streamMetadata = reader.getStreamMetadata();

      // Set up the writeParam
      TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.CHINESE);
      tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

      // Get tif writer and set output to file
      Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff");
      ImageWriter writer = writers.next();

      BufferedImage bi = reader.read(0);
      IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0));
      tempFile = tempImageFile(imageFile);
      ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
      writer.setOutput(ios);
      writer.write(streamMetadata, image, tiffWriteParam);
      ios.close();

      writer.dispose();
      reader.dispose();

    } catch (IOException e) {
      e.printStackTrace();
    }
    return tempFile;
  }
  @Override
  public void writeImage(RenderedImage image, String mimeType, float quality, OutputStream out)
      throws IOException {
    if ("image/jpeg".equals(mimeType)) {
      // Find a JPEG writer.
      ImageWriter writer = null;
      Iterator<ImageWriter> iter = ImageIO.getImageWritersByMIMEType(mimeType);
      if (iter.hasNext()) {
        writer = iter.next();
      }
      JPEGImageWriteParam iwp = new JPEGImageWriteParam(null);
      iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      iwp.setCompressionQuality(quality);

      // Prepare output file.
      ImageOutputStream ios = ImageIO.createImageOutputStream(out);
      writer.setOutput(ios);

      // Write the image.
      writer.write(null, new IIOImage(image, null, null), iwp);

      // Cleanup.
      ios.flush();
      writer.dispose();
      ios.close();
    } else {
      ImageIO.write(image, "png", out);
    }
  }
  /**
   * Salva BufferedImage no arquivo informado na prop<br>
   *
   * <p><b>Exemplo:><br>
   * <code>salvarImagem(img)</code>
   *
   * @param img BufferedImage a ser salva
   * @author roberto
   */
  private void salvarImagem(BufferedImage img) {

    ImageWriter writer = null;
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(formatoImagem);

    if (iter.hasNext()) {

      writer = (ImageWriter) iter.next();
    }

    ImageOutputStream ios;
    try {

      ios = ImageIO.createImageOutputStream(new File(prop.getProp("dirImg")));
      writer.setOutput(ios);

      ImageWriteParam param = new JPEGImageWriteParam(java.util.Locale.getDefault());
      param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      param.setCompressionQuality(1);

      writer.write(null, new IIOImage(img, null, null), param);

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Gets pixel data of an <code>IIOImage</code> object.
   *
   * @param image an <code>IIOImage</code> object
   * @return a byte buffer of pixel data
   * @throws Exception
   */
  public static ByteBuffer getImageByteBuffer(IIOImage image) throws IOException {
    // Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get tif writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

    if (writer == null) {
      throw new RuntimeException(
          "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
    }

    // Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(
        streamMetadata, new IIOImage(image.getRenderedImage(), null, null), tiffWriteParam);
    //        writer.write(image.getRenderedImage());
    writer.dispose();
    //        ImageIO.write(image.getRenderedImage(), "tiff", ios); // this can be used in lieu of
    // writer
    ios.seek(0);
    BufferedImage bi = ImageIO.read(ios);
    return convertImageData(bi);
  }
示例#8
0
  /**
   * Gets pixel data of an <code>IIOImage</code> object.
   *
   * @param oimage an <code>IIOImage</code> object
   * @return a byte buffer of pixel data
   * @throws Exception
   */
  public static ByteBuffer getImageByteBuffer(BufferedImage oimage) throws IOException {
    // Get tif writer and set output to file
    ImageWriter writer = new TIFFImageWriterSpi().createWriterInstance();

    // Set up the writeParam
    // We are using the old JAI ImageIO plugin, because for some reason, OCR don't work with
    // TwelveMonkeys' plugin
    ImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(streamMetadata, new IIOImage(oimage, null, null), tiffWriteParam);
    writer.dispose();

    // Read the writed image
    ios.seek(0);
    ImageReader reader = new TIFFImageReaderSpi().createReaderInstance();
    ImageReadParam param = reader.getDefaultReadParam();
    reader.setInput(ios, true, true);
    BufferedImage bi;
    try {
      bi = reader.read(0, param);
    } finally {
      reader.dispose();
      ios.close();
    }

    return convertImageData(bi);
  }
示例#9
0
  @SuppressWarnings("unchecked")
  public void write() throws IOException {
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(EXTENSION);
    ImageWriter writer = writers.next();

    ImageWriteParam param = writer.getDefaultWriteParam();

    IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);

    if (metadata instanceof com.sun.imageio.plugins.png.PNGMetadata) {
      com.sun.imageio.plugins.png.PNGMetadata pngMetadata =
          (com.sun.imageio.plugins.png.PNGMetadata) metadata;

      ArrayList keyword = pngMetadata.tEXt_keyword;
      ArrayList text = pngMetadata.tEXt_text;

      for (String key : this.metadata.keySet()) {
        if (keyword == null) keyword = new ArrayList();
        if (text == null) text = new ArrayList();

        keyword.add(key);
        text.add(this.metadata.get(key));
      }

      pngMetadata.tEXt_keyword = keyword;
      pngMetadata.tEXt_text = text;
    }

    IIOImage iioi = new IIOImage(image, null, metadata);

    ImageOutputStream ios = ImageIO.createImageOutputStream(file);
    writer.setOutput(ios);

    writer.write(iioi);
  }
示例#10
0
 /**
  * store BufferedImage to file
  *
  * @param image BufferedImage
  * @param outputFile output image file
  * @param quality quality of output image
  * @return true success, else fail
  */
 public static boolean storeImage(BufferedImage image, File outputFile, float quality) {
   try {
     // reconstruct folder structure for image file output
     if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists()) {
       outputFile.getParentFile().mkdirs();
     }
     if (outputFile.exists()) {
       outputFile.delete();
     }
     // get image file suffix
     String extName = "gif";
     // get registry ImageWriter for specified image suffix
     Iterator writers = ImageIO.getImageWritersByFormatName(extName);
     ImageWriter imageWriter = (ImageWriter) writers.next();
     // set image output params
     ImageWriteParam params = new JPEGImageWriteParam(null);
     params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
     params.setCompressionQuality(quality);
     params.setProgressiveMode(javax.imageio.ImageWriteParam.MODE_DISABLED);
     params.setDestinationType(
         new ImageTypeSpecifier(
             IndexColorModel.getRGBdefault(),
             IndexColorModel.getRGBdefault().createCompatibleSampleModel(16, 16)));
     // writer image to file
     ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputFile);
     imageWriter.setOutput(imageOutputStream);
     imageWriter.write(null, new IIOImage(image, null, null), params);
     imageOutputStream.close();
     imageWriter.dispose();
     return true;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return false;
 }
 /**
  * Creates an image file of the specified format.
  *
  * @param file The file where to write the image.
  * @param format One of the follow types: jpeg, png.
  * @throws Exception Thrown if an error occurred while encoding the image.
  */
 public void createImageFile(File file, String format) throws Exception {
   Iterator writers = ImageIO.getImageWritersByFormatName(format);
   ImageWriter writer = (ImageWriter) writers.next();
   ImageOutputStream ios = ImageIO.createImageOutputStream(file);
   writer.setOutput(ios);
   writer.write(new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB));
   ios.close();
 }
  /**
   * 生成随机默认头像,如果存在原图,则查询各个尺寸头像,对不存在的头像重新用原图生成
   *
   * @param userId
   * @param userName
   * @return
   */
  public void avatarGenerate(String userId, String userName) {

    // 获取缩略名字
    userName = DefaultAvatarGeneratorService.obatainName(userName);

    // 判断是否有初始头像,如果有用初始头像切割小头像,然后组装
    // 如果没有则随机选择一个初始头像,添加姓名水印后切割小头像,其实是一种容错机制
    GridFSDBFile intinalAvatarFile =
        imageStoreService.get(AvatarIdGenerator.obtainMobileLargeAvatarId(userId));

    // 要裁剪的尺寸
    List<Double> thumbnailSizeList = SnapFileConfigUtils.obtainAvatarScaleSizes();
    int number = 0;
    BufferedImage bimage = null;
    if (intinalAvatarFile == null) {

      Random random = new Random();
      number = random.nextInt(DefaultAvatarCacheService.DEFAULT_AVATAR_NUMBER);
      number++;
      bimage = DefaultAvatarCacheService.obtainCacheRandomAvatar(number);

      // 如果姓名不为空,加水印随机图片
      if (!StringUtils.isEmpty(userName)) {
        drawName(bimage, userName);
      }
    } else {
      try {
        bimage = ImageIO.read(intinalAvatarFile.getInputStream());
        thumbnailSizeList = this.obtainThumbnailSizeList(userId);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    int width = bimage.getWidth();
    int height = bimage.getHeight();

    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    ImageOutputStream imOut;
    try {
      imOut = ImageIO.createImageOutputStream(bs);

      ImageIO.write(bimage, "png", imOut);

      // 存储原图到数据库
      imageService.uploadTempLogo(new ByteArrayInputStream(bs.toByteArray()), userId);

    } catch (IOException e) {
      Logger.error("上传随机头像出错", e);
      e.printStackTrace();
    }

    if (!thumbnailSizeList.isEmpty()) {
      // 生成切割小图片,存入数据库
      imageService.rectAndStoreAvatar(
          userId, 0, 0, width, height, thumbnailSizeList, AvatarIdGenerator.USER_TYPE);
    }
  }
示例#13
0
  /** 生成验证码 */
  public void getImageCode() {
    long beginRunTime = 0;
    if (logger.isDebugEnabled()) {
      beginRunTime = System.currentTimeMillis();
      logger.debug("enter getImageCode method.");
    }
    int width = 70;
    int height = 20;
    try {
      Random random = new Random();
      BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      Graphics g = image.getGraphics();
      g.setColor(Color.WHITE);
      g.fillRect(0, 0, width, height);
      g.setFont(new Font("Arial", Font.PLAIN, 18));

      String code = RandomStringUtils.random(5, true, true);
      Pattern p = Pattern.compile(pattern);
      Matcher matcher = p.matcher(code);
      while (matcher.find()) {

        code = RandomStringUtils.random(5, true, true);
        matcher = p.matcher(code);
      }
      if (logger.isDebugEnabled()) {
        logger.debug("---code:" + code);
      }
      for (int i = 0; i < code.length(); i++) {
        g.setColor(
            new Color(
                20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        g.drawString(
            String.valueOf(code.charAt(i)),
            (int) ((width * 0.20) * (i + 0.06)),
            (int) (height * 0.8));
      }
      HttpServletRequest request = ServletActionContext.getRequest();
      HttpServletResponse response = ServletActionContext.getResponse();
      response.setHeader("Pragma", "No-cache");
      response.setHeader("Cache-Control", "no-cache");
      response.setDateHeader("Expires", 0);
      request.getSession().setAttribute("code", code);
      g.dispose();
      ServletOutputStream output = response.getOutputStream();
      ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
      ImageIO.write(image, "JPEG", imageOut);
      imageOut.flush();
      imageOut.close();
      output.flush();
    } catch (IOException e) {
      e.printStackTrace();
    }
    if (logger.isDebugEnabled()) {
      long takeTime = System.currentTimeMillis() - beginRunTime;
      logger.debug("exit getImageCode method.takeTime:" + takeTime + "ms");
    }
  }
 private static void write(File f, boolean raw, BufferedImage image) throws IOException {
   Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("ppm");
   assertTrue(writers.hasNext());
   ImageWriter writer = writers.next();
   PNMImageWriteParam params = (PNMImageWriteParam) writer.getDefaultWriteParam();
   params.setRaw(raw);
   ImageOutputStream ios = ImageIO.createImageOutputStream(f);
   writer.setOutput(ios);
   writer.write(null, new IIOImage(image, null, null), params);
   writer.dispose();
   ios.close();
 }
  /**
   * Creates a list of TIFF image files from an image file. It basically converts images of other
   * formats to TIFF format, or a multi-page TIFF image to multiple TIFF image files.
   *
   * @param imageFile input image file
   * @param index an index of the page; -1 means all pages, as in a multi-page TIFF image
   * @return a list of TIFF image files
   * @throws Exception
   */
  public static List<File> createTiffFiles(File imageFile, int index) throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    String imageFileName = imageFile.getName();
    String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);

    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
    ImageReader reader = readers.next();

    if (reader == null) {
      throw new RuntimeException(
          "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
    }

    ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
    reader.setInput(iis);
    // Read the stream metadata
    //        IIOMetadata streamMetadata = reader.getStreamMetadata();

    // Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get tif writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

    // Read the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    int imageTotal = reader.getNumImages(true);

    for (int i = 0; i < imageTotal; i++) {
      // all if index == -1; otherwise, only index-th
      if (index == -1 || i == index) {
        //                BufferedImage bi = reader.read(i);
        //                IIOImage oimage = new IIOImage(bi, null, reader.getImageMetadata(i));
        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
        File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
        ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile);
        writer.setOutput(ios);
        writer.write(streamMetadata, oimage, tiffWriteParam);
        ios.close();
        tiffFiles.add(tiffFile);
      }
    }
    writer.dispose();
    reader.dispose();

    return tiffFiles;
  }
  private static byte[] convertChartToByteArray(
      Chart chartDetails, JFreeChart chart, int width, int height)
      throws IOException, IIOInvalidTreeException {
    BufferedImage buffImg =
        chart.createBufferedImage(
            width, height, BufferedImage.BITMASK | BufferedImage.SCALE_SMOOTH, null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();

    ImageWriteParam writeParam = writer.getDefaultWriteParam();
    ImageTypeSpecifier typeSpecifier =
        ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
    IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);

    if (chartDetails != null) {
      if (chartDetails.getId() == null) {
        chartDetails.setId("%ID%");
      }
      IIOMetadataNode textEntry = new IIOMetadataNode("tEXtEntry");
      textEntry.setAttribute("keyword", "chart-google-data");
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(bout);
      objectOutputStream.writeObject(chartDetails);
      objectOutputStream.flush();
      textEntry.setAttribute(
          "value",
          (String)
              ChartRendererFactory.getRendererForOutput(ChartRendererGoogleTools.TYPE)
                  .renderChart(chartDetails));

      IIOMetadataNode text = new IIOMetadataNode("tEXt");
      text.appendChild(textEntry);

      IIOMetadataNode root = new IIOMetadataNode("javax_imageio_png_1.0");
      root.appendChild(text);

      metadata.mergeTree("javax_imageio_png_1.0", root);
    }
    // setDPI(metadata);

    final ImageOutputStream stream = ImageIO.createImageOutputStream(baos);
    try {
      writer.setOutput(stream);
      writer.write(metadata, new IIOImage(buffImg, null, metadata), writeParam);
    } finally {
      stream.close();
    }

    byte[] bytes = baos.toByteArray(); // ChartUtilities.encodeAsPNG(buffImg, true, 9);
    return bytes;
  }
示例#17
0
  /**
   * @see ImageWriter#writeImage(java.awt.image.RenderedImage, java.io.OutputStream,
   *     ImageWriterParams)
   */
  public void writeImage(RenderedImage image, OutputStream out, ImageWriterParams params)
      throws IOException {
    Iterator iter;
    iter = ImageIO.getImageWritersByMIMEType(getMIMEType());
    javax.imageio.ImageWriter iiowriter = null;
    try {
      iiowriter = (javax.imageio.ImageWriter) iter.next();
      if (iiowriter != null) {
        iiowriter.addIIOWriteWarningListener(this);

        ImageOutputStream imgout = null;
        try {
          imgout = ImageIO.createImageOutputStream(out);
          ImageWriteParam iwParam = getDefaultWriteParam(iiowriter, image, params);

          ImageTypeSpecifier type;
          if (iwParam.getDestinationType() != null) {
            type = iwParam.getDestinationType();
          } else {
            type = ImageTypeSpecifier.createFromRenderedImage(image);
          }

          // Handle metadata
          IIOMetadata meta = iiowriter.getDefaultImageMetadata(type, iwParam);
          // meta might be null for some JAI codecs as they don't support metadata
          if (params != null && meta != null) {
            meta = updateMetadata(meta, params);
          }

          // Write image
          iiowriter.setOutput(imgout);
          IIOImage iioimg = new IIOImage(image, null, meta);
          iiowriter.write(null, iioimg, iwParam);
        } finally {
          if (imgout != null) {
            System.err.println("closing");
            imgout.close();
          }
        }
      } else {
        throw new UnsupportedOperationException(
            "No ImageIO codec for writing " + getMIMEType() + " is available!");
      }
    } finally {
      if (iiowriter != null) {
        System.err.println("disposing");
        iiowriter.dispose();
      }
    }
  }
示例#18
0
  public static void main(String[] args) throws IOException {
    List<Color> colorlist = new ArrayList<Color>();
    for (int i = 0; i < 9000; i++) {
      if (new Random().nextBoolean()) colorlist.add(Color.red);
      else if (i > 600) colorlist.add(Color.green);
      else colorlist.add(Color.yellow);
    }
    int width = 600;
    int height = 30;
    BufferedImage image = null;
    Graphics2D g2 = null;
    int step = width / colorlist.size();
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);

    if (step >= 1) {
      image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      g2 = (Graphics2D) image.getGraphics();
      g2.setBackground(Color.WHITE);
      for (int i = 0; i < colorlist.size(); i++) {
        g2.setColor(colorlist.get(i));
        g2.fillRect(i * step, 0, i * step + step, height);
      }
    } else {
      image = new BufferedImage(colorlist.size(), height, BufferedImage.TYPE_INT_RGB);
      g2 = (Graphics2D) image.getGraphics();
      g2.setBackground(Color.WHITE);
      for (int i = 0; i < colorlist.size(); i++) {
        g2.setColor(colorlist.get(i));
        g2.drawLine(i, 0, i, height);
      }
    }
    g2.dispose();

    Image scaleImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);

    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    g2 = (Graphics2D) image.getGraphics();
    g2.drawImage(scaleImage, 0, 0, null);
    g2.dispose();

    ImageIO.write(image, "GIF", imOut);
    byte[] contentByte = bs.toByteArray();
    FileOutputStream f = new FileOutputStream("d:\\test.gif");
    f.write(contentByte);
    f.flush();
    f.close();
    bs.close();
    imOut.close();
  }
示例#19
0
 public void compressJpegFile(
     File infile, File outfile, float compressionQuality, int widthCanvas, int heightCanvas)
     throws IOException {
   // Retrieve jpg image to be compressed
   BufferedImage rendImage = ImageIO.read(infile);
   widthFile = rendImage.getWidth();
   heightFile = rendImage.getHeight();
   double aspectRatioCanvas = widthCanvas / heightCanvas;
   double aspectRatioFile = widthFile / heightFile;
   widthFile = widthCanvas;
   heightFile = widthCanvas / aspectRatioFile;
   if (heightFile > heightCanvas) {
     heightFile = heightCanvas;
     widthFile = heightCanvas * aspectRatioFile;
   }
   this.width = (int) widthFile;
   this.height = (int) heightFile;
   ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(rendImage);
   BufferedImage outImage = its.createBufferedImage(width, height);
   Graphics2D graphics2D = outImage.createGraphics();
   graphics2D.setRenderingHint(
       RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
   //         graphics2D.drawRenderedImage(rendImage, new AffineTransform());
   graphics2D.drawImage(rendImage, 0, 0, width, height, null);
   // Find a jpeg writer
   ImageWriter writer = null;
   Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
   if (iter.hasNext()) {
     writer = (ImageWriter) iter.next();
   }
   // Prepare output file
   ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
   writer.setOutput(ios);
   // Set the compression quality
   ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
   iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
   iwparam.setCompressionQuality(compressionQuality);
   // Write the image
   writer.write(null, new IIOImage(outImage, null, null), iwparam);
   // infile.delete();
   // Cleanup
   ios.flush();
   writer.dispose();
   ios.close();
   // return
 }
示例#20
0
  private static byte[] toPng(BufferedImage bufferedImage) throws IOException {
    ImageWriter imageWriter = getPngImageWriter();
    try {
      // set quality
      ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream);

      imageWriter.setOutput(imageOutputStream);
      IIOImage iioImage = new IIOImage(bufferedImage, null, null);
      imageWriter.write(null, iioImage, imageWriteParam);

      return (byteArrayOutputStream.toByteArray());
    } finally {
      imageWriter.dispose();
    }
  }
示例#21
0
 public String execute() throws Exception {
   // 在内存中创建图象
   int width = 85, height = 20;
   BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   // 获取图形上下文
   Graphics g = image.getGraphics();
   // 生成随机类
   Random random = new Random();
   // 设定背景色
   g.setColor(getRandColor(200, 250));
   g.fillRect(0, 0, width, height);
   // 设定字体
   g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
   // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
   g.setColor(getRandColor(160, 200));
   for (int i = 0; i < 155; i++) {
     int x = random.nextInt(width);
     int y = random.nextInt(height);
     int xl = random.nextInt(12);
     int yl = random.nextInt(12);
     g.drawLine(x, y, x + xl, y + yl);
   }
   // 取随机产生的认证码(6位数字)
   String sRand = "";
   for (int i = 0; i < 6; i++) {
     String rand = String.valueOf(random.nextInt(10));
     sRand += rand;
     // 将认证码显示到图象中
     g.setColor(
         new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
     // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
     g.drawString(rand, 13 * i + 6, 16);
   }
   // 将认证码存入SESSION
   ActionContext.getContext().getSession().put("identifying_code", sRand);
   // 图象生效
   g.dispose();
   ByteArrayOutputStream output = new ByteArrayOutputStream();
   ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
   ImageIO.write(image, "JPEG", imageOut);
   imageOut.close();
   ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
   this.setInputStream(input);
   return SUCCESS;
 }
示例#22
0
 /**
  * 生成包含logo的二维码
  *
  * @param content
  * @param imgType
  * @param size
  * @param logoImage
  * @return
  */
 public InputStream encodeQRCodeHasLogo(
     String content, String imgType, int size, LogoImage logoImage) {
   InputStream is = null;
   BufferedImage bufImg = this.generateQRCodeImage(content, imgType, size, logoImage);
   ByteArrayOutputStream bs = new ByteArrayOutputStream();
   ImageOutputStream imOut = null;
   try {
     imOut = ImageIO.createImageOutputStream(bs);
     ImageIO.write(bufImg, imgType, imOut);
     is = new ByteArrayInputStream(bs.toByteArray());
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     this.close(bs);
     this.close(imOut);
   }
   return is;
 }
  public void processImage(BufferedImage image, OutputStream out) throws IOException {

    if (image.getColorModel().hasAlpha()) {
      // Javas JPEG writes has a bug when the image has alpha transparency
      // see http://stackoverflow.com/questions/4386446/problem-using-imageio-write-jpg-file

      BufferedImage imageRGB =
          new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
      Graphics2D g = imageRGB.createGraphics();
      g.drawImage(image, null, 0, 0);
      g.dispose();
      image = imageRGB;
    }

    ImageOutputStream imageOut = ImageIO.createImageOutputStream(out);
    jpegImageWriter.setOutput(imageOut);
    IIOImage ioImage = new IIOImage(image, null, null);
    jpegImageWriter.write(null, ioImage, iwp);
  }
示例#24
0
  public static byte[] getImageBytes(Image image, String type) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    BufferedImage bufImage = convertToBufferedImage(image);
    ImageWriter writer = null;
    Iterator i = ImageIO.getImageWritersByMIMEType(type);
    if (i.hasNext()) {
      writer = (ImageWriter) i.next();
    }
    if (writer != null) {
      ImageOutputStream stream = null;
      stream = ImageIO.createImageOutputStream(baos);
      writer.setOutput(stream);
      writer.write(bufImage);
      stream.close();
      return baos.toByteArray();
    }
    return null;
  }
  public static boolean compressPic(String srcFilePath, String descFilePath) {
    File file = null;
    BufferedImage src = null;
    FileOutputStream out = null;
    ImageWriter imgWrier;
    ImageWriteParam imgWriteParams;

    // 指定写图片的方式为 jpg
    imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
    imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
    // 要使用压缩,必须指定压缩方式为MODE_EXPLICIT
    imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
    // 这里指定压缩的程度,参数qality是取值0~1范围内,
    imgWriteParams.setCompressionQuality((float) 0.1);
    imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
    ColorModel colorModel = ColorModel.getRGBdefault();
    // 指定压缩时使用的色彩模式
    imgWriteParams.setDestinationType(
        new javax.imageio.ImageTypeSpecifier(
            colorModel, colorModel.createCompatibleSampleModel(16, 16)));

    try {
      if (StringUtils.isBlank(srcFilePath)) {
        return false;
      } else {
        file = new File(srcFilePath);
        src = ImageIO.read(file);
        out = new FileOutputStream(descFilePath);

        imgWrier.reset();
        // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造
        imgWrier.setOutput(ImageIO.createImageOutputStream(out));
        // 调用write方法,就可以向输入流写图片
        imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
        out.flush();
        out.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }
  public static List<File> createTiffFiles(List<IIOImage> imageList, int index, int dpiX, int dpiY)
      throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    // Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get tif writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

    if (writer == null) {
      throw new RuntimeException(
          "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
    }

    // Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    // all if index == -1; otherwise, only index-th
    for (IIOImage oimage : (index == -1 ? imageList : imageList.subList(index, index + 1))) {
      if (dpiX != 0 && dpiY != 0) {
        // Get the default image metadata.
        ImageTypeSpecifier imageType =
            ImageTypeSpecifier.createFromRenderedImage(oimage.getRenderedImage());
        IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, null);
        imageMetadata = setDPIViaAPI(imageMetadata, dpiX, dpiY);
        oimage.setMetadata(imageMetadata);
      }

      File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
      ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile);
      writer.setOutput(ios);
      writer.write(streamMetadata, oimage, tiffWriteParam);
      ios.close();
      tiffFiles.add(tiffFile);
    }
    writer.dispose();

    return tiffFiles;
  }
示例#27
0
  public byte[] generateCheckCodeImage() {
    try {
      Integer width = Integer.valueOf(60);
      Integer height = Integer.valueOf(20);
      Integer wordLength = Integer.valueOf(4);
      BufferedImage image = new BufferedImage(width, height, 1);
      Graphics g = image.getGraphics();
      Random random = new Random(System.currentTimeMillis());
      g.setColor(new Color(200, 200, 200));
      g.fillRect(0, 0, width, height);
      g.setFont(new Font("Times New Roman", 0, 18));
      for (int i = 0; i < 155; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        g.drawLine(x, y, x + xl, y + yl);
      }

      autoGenerCheckCode = "";
      for (int i = 0; i < wordLength.intValue(); i++) {
        String rand = (new StringBuilder(String.valueOf(random.nextInt(10)))).toString();
        autoGenerCheckCode =
            (new StringBuilder(String.valueOf(autoGenerCheckCode))).append(rand).toString();
        g.setColor(
            new Color(
                20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        g.drawString(rand, 13 * i + 4, 16);
      }

      g.dispose();
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
      ImageIO.write(image, "JPEG", imageOut);
      imageOut.close();
      return output.toByteArray();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
示例#28
0
  /**
   * 图片截取
   *
   * @param file
   * @param newName
   * @param path
   * @param x
   * @param y
   * @param width
   * @param height
   * @return author:caobo date:Oct 14, 2009 12:38:05 PM
   */
  public static File cutting(
      File file, String newName, String path, int x, int y, int width, int height) {
    ImageOutputStream out = null;
    InputStream is = null;
    ImageInputStream iis = null;
    try {
      String endName = file.getName();
      endName = endName.substring(endName.lastIndexOf(".") + 1);
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(endName);
      ImageReader reader = (ImageReader) readers.next();
      is = new FileInputStream(file);
      iis = ImageIO.createImageInputStream(is);
      reader.setInput(iis, true);

      ImageReadParam param = reader.getDefaultReadParam();
      Rectangle rect = new Rectangle(x, y, width, height);
      param.setSourceRegion(rect);
      BufferedImage bi = reader.read(0, param);
      File newFile = new File(path);

      if (!newFile.exists()) newFile.mkdirs();
      newFile = new File(path, newName);
      out = ImageIO.createImageOutputStream(new FileOutputStream(newFile));
      ImageIO.write(bi, endName, out);
      file = newFile;
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        iis.close();
        is.close();
        out.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return file;
  }
示例#29
0
  public InputStream getSpectrumImage(List<Color> colorlist, int width, int height)
      throws IOException {
    BufferedImage image = null;
    Graphics2D g2 = null;
    int step = width / colorlist.size();

    if (step >= 1) {
      image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      g2 = (Graphics2D) image.getGraphics();
      g2.setBackground(Color.WHITE);
      for (int i = 0; i < colorlist.size(); i++) {
        g2.setColor(colorlist.get(i));
        g2.fillRect(i * step, 0, i * step + step, height);
      }
    } else {
      image = new BufferedImage(colorlist.size(), height, BufferedImage.TYPE_INT_RGB);
      g2 = (Graphics2D) image.getGraphics();
      g2.setBackground(Color.WHITE);
      for (int i = 0; i < colorlist.size(); i++) {
        g2.setColor(colorlist.get(i));
        g2.drawLine(i, 0, i, height);
      }
    }
    g2.dispose();

    Image scaleImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);

    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    g2 = (Graphics2D) image.getGraphics();
    g2.drawImage(scaleImage, 0, 0, null);
    g2.dispose();

    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
    ImageIO.write(image, "GIF", imOut);
    InputStream istream = new ByteArrayInputStream(bs.toByteArray());
    return istream;
  }
  @SuppressWarnings("unused")
  private boolean saveJpeg(int[] byteArray, int width, int height, int dpi, String file) {
    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    WritableRaster wr = bufferedImage.getRaster();
    wr.setPixels(0, 0, width, height, byteArray);

    try {
      // Image writer
      JPEGImageWriter imageWriter =
          (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(file));
      imageWriter.setOutput(ios);

      // Compression
      JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
      jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
      jpegParams.setCompressionQuality(0.85f);

      // Metadata (dpi)
      IIOMetadata data =
          imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), jpegParams);
      Element tree = (Element) data.getAsTree("javax_imageio_jpeg_image_1.0");
      Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
      jfif.setAttribute("Xdensity", Integer.toString(dpi));
      jfif.setAttribute("Ydensity", Integer.toString(dpi));
      jfif.setAttribute("resUnits", "1"); // density is dots per inch

      // Write and clean up
      imageWriter.write(data, new IIOImage(bufferedImage, null, null), jpegParams);
      ios.close();
      imageWriter.dispose();
    } catch (Exception e) {
      return false;
    }

    return true;
  }