예제 #1
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);
    }
  }
  @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);
    }
  }
예제 #3
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");
    }
  }
예제 #4
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
 }
  /** Releases resources held by this {@link AbstractGridCoverageWriter}. */
  public void dispose() {
    if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Disposing writer:" + destination);

    if (outStream != null) {
      try {
        outStream.flush();

      } catch (IOException e) {

      } finally {
        try {
          outStream.close();
        } catch (Throwable e) {

        }
      }
    }
  }
 private void writeRawData(File levelDir, int tileX, int tileY, int[] data, boolean rawZip)
     throws IOException {
   final String baseName = tileX + "-" + tileY + ".raw";
   if (rawZip) {
     final File file = new File(levelDir, baseName + ".zip");
     final ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
     zipOutputStream.putNextEntry(new ZipEntry(baseName));
     final ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(zipOutputStream);
     imageOutputStream.writeInts(data, 0, data.length);
     imageOutputStream.flush();
     zipOutputStream.closeEntry();
     zipOutputStream.close();
   } else {
     final File file = new File(levelDir, baseName);
     FileImageOutputStream outputStream = new FileImageOutputStream(file);
     outputStream.writeInts(data, 0, data.length);
     outputStream.close();
   }
 }
예제 #7
0
  public static void addWatermark(File srcFile, File destFile, File watermarkFile, int alpha) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists()) {
      try {
        FileUtils.copyFile(srcFile, destFile);
      } catch (IOException e) {
        e.printStackTrace();
      }
      return;
    }
    if (type == Type.jdk) {
      Graphics2D graphics2D = null;
      ImageOutputStream imageOutputStream = null;
      ImageWriter imageWriter = null;
      try {
        BufferedImage srcBufferedImage = ImageIO.read(srcFile);
        int srcWidth = srcBufferedImage.getWidth();
        int srcHeight = srcBufferedImage.getHeight();
        BufferedImage destBufferedImage =
            new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
        graphics2D = destBufferedImage.createGraphics();
        graphics2D.setBackground(BACKGROUND_COLOR);
        graphics2D.clearRect(0, 0, srcWidth, srcHeight);
        graphics2D.drawImage(srcBufferedImage, 0, 0, null);
        graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

        BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
        int watermarkImageWidth = watermarkBufferedImage.getWidth();
        int watermarkImageHeight = watermarkBufferedImage.getHeight();
        int x = srcWidth - watermarkImageWidth;
        int y = srcHeight - watermarkImageHeight;

        graphics2D.drawImage(
            watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

        imageOutputStream = ImageIO.createImageOutputStream(destFile);
        imageWriter =
            ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                .next();
        imageWriter.setOutput(imageOutputStream);
        ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
        imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
        imageOutputStream.flush();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (graphics2D != null) {
          graphics2D.dispose();
        }
        if (imageWriter != null) {
          imageWriter.dispose();
        }
        if (imageOutputStream != null) {
          try {
            imageOutputStream.close();
          } catch (IOException e) {
          }
        }
      }
    } else {
      IMOperation operation = new IMOperation();
      operation.dissolve(alpha);
      operation.quality((double) DEST_QUALITY);
      operation.addImage(watermarkFile.getPath());
      operation.addImage(srcFile.getPath());
      operation.addImage(destFile.getPath());
      if (type == Type.graphicsMagick) {
        CompositeCmd compositeCmd = new CompositeCmd(true);
        if (graphicsMagickPath != null) {
          compositeCmd.setSearchPath(graphicsMagickPath);
        }
        try {
          compositeCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      } else {
        CompositeCmd compositeCmd = new CompositeCmd(false);
        if (imageMagickPath != null) {
          compositeCmd.setSearchPath(imageMagickPath);
        }
        try {
          compositeCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      }
    }
  }
예제 #8
0
  public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
      Graphics2D graphics2D = null;
      ImageOutputStream imageOutputStream = null;
      ImageWriter imageWriter = null;
      try {
        BufferedImage srcBufferedImage = ImageIO.read(srcFile);
        int srcWidth = srcBufferedImage.getWidth();
        int srcHeight = srcBufferedImage.getHeight();
        int width = destWidth;
        int height = destHeight;
        if (srcHeight >= srcWidth) {
          width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
        } else {
          height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
        }
        BufferedImage destBufferedImage =
            new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
        graphics2D = destBufferedImage.createGraphics();
        graphics2D.setBackground(BACKGROUND_COLOR);
        graphics2D.clearRect(0, 0, destWidth, destHeight);
        graphics2D.drawImage(
            srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
            (destWidth / 2) - (width / 2),
            (destHeight / 2) - (height / 2),
            null);

        imageOutputStream = ImageIO.createImageOutputStream(destFile);
        imageWriter =
            ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                .next();
        imageWriter.setOutput(imageOutputStream);
        ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
        imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
        imageOutputStream.flush();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (graphics2D != null) {
          graphics2D.dispose();
        }
        if (imageWriter != null) {
          imageWriter.dispose();
        }
        if (imageOutputStream != null) {
          try {
            imageOutputStream.close();
          } catch (IOException e) {
          }
        }
      }
    } else {
      IMOperation operation = new IMOperation();
      operation.thumbnail(destWidth, destHeight);
      operation.gravity("center");
      operation.background(toHexEncoding(BACKGROUND_COLOR));
      operation.extent(destWidth, destHeight);
      operation.quality((double) DEST_QUALITY);
      operation.addImage(srcFile.getPath());
      operation.addImage(destFile.getPath());
      if (type == Type.graphicsMagick) {
        ConvertCmd convertCmd = new ConvertCmd(true);
        if (graphicsMagickPath != null) {
          convertCmd.setSearchPath(graphicsMagickPath);
        }
        try {
          convertCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      } else {
        ConvertCmd convertCmd = new ConvertCmd(false);
        if (imageMagickPath != null) {
          convertCmd.setSearchPath(imageMagickPath);
        }
        try {
          convertCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      }
    }
  }
예제 #9
0
  /** Upload scanned document to OpenKM */
  public static String createDocument(
      String token,
      String path,
      String fileName,
      String fileType,
      String url,
      List<BufferedImage> images)
      throws MalformedURLException, IOException {
    log.info(
        "createDocument("
            + token
            + ", "
            + path
            + ", "
            + fileName
            + ", "
            + fileType
            + ", "
            + url
            + ", "
            + images
            + ")");
    File tmpDir = createTempDir();
    File tmpFile = new File(tmpDir, fileName + "." + fileType);
    ImageOutputStream ios = ImageIO.createImageOutputStream(tmpFile);
    String response = "";

    try {
      if ("pdf".equals(fileType)) {
        ImageUtils.writePdf(images, ios);
      } else if ("tif".equals(fileType)) {
        ImageUtils.writeTiff(images, ios);
      } else {
        if (!ImageIO.write(images.get(0), fileType, ios)) {
          throw new IOException("Not appropiated writer found!");
        }
      }

      ios.flush();
      ios.close();

      if (token != null) {
        // Send image
        HttpClient client = new DefaultHttpClient();
        MultipartEntity form = new MultipartEntity();
        form.addPart("file", new FileBody(tmpFile));
        form.addPart("path", new StringBody(path, Charset.forName("UTF-8")));
        form.addPart("action", new StringBody("0")); // FancyFileUpload.ACTION_INSERT
        HttpPost post = new HttpPost(url + "/frontend/FileUpload;jsessionid=" + token);
        post.setHeader("Cookie", "jsessionid=" + token);
        post.setEntity(form);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
      } else {
        // Store in disk
        String home = System.getProperty("user.home");
        File dst = new File(home, tmpFile.getName());
        copyFile(tmpFile, dst);
        response = "Image copied to " + dst.getPath();
      }
    } finally {
      FileUtils.deleteQuietly(tmpDir);
    }

    log.info("createDocument: " + response);
    return response;
  }
예제 #10
0
 @Override
 public void flush() throws IOException {
   if (forwardFlushAndClose) {
     out.flush();
   }
 }