Example #1
0
 /**
  * 按宽度高度压缩图片文件<br>
  * 先保存原文件,再压缩、上传
  *
  * @param oldFile 要进行压缩的文件全路径
  * @param newFile 新文件
  * @param width 宽度
  * @param height 高度
  * @param quality 质量
  * @return 返回压缩后的文件的全路径
  */
 @SuppressWarnings("restriction")
 public static String zipWidthHeightImageFile(
     File oldFile, File newFile, int width, int height, float quality) {
   if (oldFile == null) {
     return null;
   }
   String newImage = null;
   try {
     /** 对服务器上的临时文件进行处理 */
     Image srcFile = ImageIO.read(oldFile);
     int w = srcFile.getWidth(null);
     int h = srcFile.getHeight(null);
     /** 宽,高设定 */
     BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
     tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
     // String filePrex = oldFile.substring(0, oldFile.indexOf('.'));
     /** 压缩后的文件名 */
     // newImage = filePrex + smallIcon+ oldFile.substring(filePrex.length());
     /** 压缩之后临时存放位置 */
     FileOutputStream out = new FileOutputStream(newFile);
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
     JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
     /** 压缩质量 */
     jep.setQuality(quality, true);
     encoder.encode(tag, jep);
     out.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return newImage;
 }
Example #2
0
  private void createImage(OutputStream out) {
    int width = 100;
    int height = 100;

    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = bi.createGraphics();

    // set background color
    g.setBackground(Color.BLUE);
    g.clearRect(0, 0, width, height);

    // set  color
    g.setColor(Color.RED);

    g.drawLine(0, 0, 99, 99);
    g.dispose();
    bi.flush();

    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
    param.setQuality(1.0f, false);
    encoder.setJPEGEncodeParam(param);

    try {
      encoder.encode(bi);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public static void saveJPG(Image img, String s) {
    BufferedImage bi =
        new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage(img, null, null);

    FileOutputStream out = null;
    try {
      out = new FileOutputStream(s);
    } catch (java.io.FileNotFoundException io) {
      System.out.println("File Not Found");
    }

    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
    param.setQuality(0.5f, false);
    encoder.setJPEGEncodeParam(param);

    try {
      encoder.encode(bi);
      out.close();
    } catch (java.io.IOException io) {
      System.out.println("IOException");
    }
  }
  /**
   * @param bufInputStream
   * @param outputStream
   */
  private void writeScaledImage(BufferedInputStream bufInputStream, OutputStream outputStream) {

    long millis = System.currentTimeMillis();
    try {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      int bytesRead = 0;
      byte[] buffer = new byte[8192];
      while ((bytesRead = bufInputStream.read(buffer, 0, 8192)) != -1) {
        bos.write(buffer, 0, bytesRead);
      }
      bos.close();

      byte[] imageBytes = bos.toByteArray();

      Image image = Toolkit.getDefaultToolkit().createImage(imageBytes);
      MediaTracker mediaTracker = new MediaTracker(new Container());
      mediaTracker.addImage(image, 0);
      mediaTracker.waitForID(0);
      // determine thumbnail size from WIDTH and HEIGHT
      int thumbWidth = 300;
      int thumbHeight = 200;
      double thumbRatio = (double) thumbWidth / (double) thumbHeight;
      int imageWidth = image.getWidth(null);
      int imageHeight = image.getHeight(null);
      double imageRatio = (double) imageWidth / (double) imageHeight;
      if (thumbRatio < imageRatio) {
        thumbHeight = (int) (thumbWidth / imageRatio);
      } else {
        thumbWidth = (int) (thumbHeight * imageRatio);
      }
      // draw original image to thumbnail image object and
      // scale it to the new size on-the-fly
      BufferedImage thumbImage =
          new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
      Graphics2D graphics2D = thumbImage.createGraphics();
      graphics2D.setRenderingHint(
          RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
      int quality = 70;
      quality = Math.max(0, Math.min(quality, 100));
      param.setQuality((float) quality / 100.0f, false);
      encoder.setJPEGEncodeParam(param);
      encoder.encode(thumbImage);
    } catch (IOException ex) {
      log.error(ex.getMessage(), ex);
    } catch (InterruptedException ex) {
      log.error(ex.getMessage(), ex);
    } finally {
      log.debug("Time for thumbnail: " + (System.currentTimeMillis() - millis) + "ms");
    }
  }
Example #5
0
 /** Derived classes should implement this method and encode the input BufferedImage as needed */
 public void encodeImage(BufferedImage buf, File imageFile) throws SVGGraphics2DIOException {
   try {
     OutputStream os = new FileOutputStream(imageFile);
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
     JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(buf);
     param.setQuality(1, false);
     encoder.encode(buf, param);
     os.flush();
     os.close();
   } catch (IOException e) {
     throw new SVGGraphics2DIOException(ERR_WRITE + imageFile.getName());
   }
 }
Example #6
0
  public static void crop(
      String src, String dest, int scaledWith, int scaledHeight, int x, int y, int w, int h)
      throws IOException {
    BufferedImage image = ImageIO.read(new File(src));
    int widthOrigin = image.getWidth();
    int heightOrigin = image.getHeight();

    if (x < 0 || y < 0 || w <= 0 || h <= 0) {
      throw new IllegalArgumentException("裁剪参数不正确");
    }

    // 需要缩放
    if (scaledWith > 0
        && scaledHeight > 0
        && scaledWith != heightOrigin
        && scaledHeight != widthOrigin) {
      BufferedImage imageScale =
          new BufferedImage(scaledWith, scaledHeight, BufferedImage.TYPE_INT_RGB);
      imageScale
          .getGraphics()
          .drawImage(
              image.getScaledInstance(scaledWith, scaledHeight, java.awt.Image.SCALE_SMOOTH),
              0,
              0,
              null);
      image = imageScale;
    } else {
      scaledWith = widthOrigin;
      scaledHeight = heightOrigin;
    }

    if (x + w > scaledWith || y + h > scaledHeight) {
      throw new IllegalArgumentException("裁剪参数不正确");
    }

    // 开始裁剪
    BufferedImage imageCrop = image.getSubimage(x, y, w, h);

    FileOutputStream newimage = null;
    try {
      newimage = new FileOutputStream(dest);
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
      JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(imageCrop);
      jep.setQuality(1.0f, true);
      encoder.encode(imageCrop, jep);
    } finally {
      if (newimage != null) {
        newimage.close();
      }
    }
  }
Example #7
0
 // write a buffered image to a jpeg file.
 protected static void saveJPG(Image img, String filename) {
   BufferedImage bi = imageToBufferedImage(img);
   FileOutputStream out = null;
   try {
     out = new FileOutputStream(filename);
   } catch (java.io.FileNotFoundException io) {
     System.out.println("File Not Found");
   }
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
   param.setQuality(0.8f, false);
   encoder.setJPEGEncodeParam(param);
   try {
     encoder.encode(bi);
     out.close();
   } catch (java.io.IOException io) {
     System.out.println("IOException");
   }
 }
Example #8
0
 /**
  * ����gifͼƬ
  *
  * @param originalFile ԭͼƬ
  * @param resizedFile ���ź��ͼƬ
  * @param newWidth ���
  * @param quality ���ű��� (�ȱ���)
  * @throws IOException
  */
 private static void resize(File originalFile, File resizedFile, int newWidth, float quality)
     throws IOException {
   if (quality < 0 || quality > 1)
     throw new IllegalArgumentException("Quality has to be between 0 and 1");
   ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
   Image i = ii.getImage();
   Image resizedImage = null;
   int iWidth = i.getWidth(null);
   int iHeight = i.getHeight(null);
   if (iWidth > iHeight)
     resizedImage = i.getScaledInstance(newWidth, newWidth * iHeight / iWidth, Image.SCALE_SMOOTH);
   else
     resizedImage = i.getScaledInstance(newWidth * iWidth / iHeight, newWidth, Image.SCALE_SMOOTH);
   // This code ensures that all the pixels in the image are loaded.
   Image temp = new ImageIcon(resizedImage).getImage();
   // Create the buffered image.
   BufferedImage bufferedImage =
       new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
   // Copy image to buffered image.
   Graphics g = bufferedImage.createGraphics();
   // Clear background and paint the image.
   g.setColor(Color.white);
   g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
   g.drawImage(temp, 0, 0, null);
   g.dispose();
   // Soften.
   float softenFactor = 0.05f;
   float[] softenArray = {
     0, softenFactor, 0, softenFactor, 1 - softenFactor * 4, softenFactor, 0, softenFactor, 0
   };
   Kernel kernel = new Kernel(3, 3, softenArray);
   ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
   bufferedImage = cOp.filter(bufferedImage, null);
   // Write the jpeg to a file.
   FileOutputStream out = new FileOutputStream(resizedFile);
   // Encodes image as a JPEG data stream
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
   param.setQuality(quality, true);
   encoder.setJPEGEncodeParam(param);
   encoder.encode(bufferedImage);
 }
Example #9
0
 /**
  * 等比例压缩图片文件<br>
  * 先保存原文件,再压缩、上传
  *
  * @param oldFile 要进行压缩的文件
  * @param newFile 新文件
  * @param width 宽度 //设置宽度时(高度传入0,等比例缩放)
  * @param height 高度 //设置高度时(宽度传入0,等比例缩放)
  * @param quality 质量
  * @return 返回压缩后的文件的全路径
  */
 public static String zipImageFile(
     File oldFile, File newFile, int width, int height, float quality) {
   if (oldFile == null) {
     return null;
   }
   try {
     /** 对服务器上的临时文件进行处理 */
     Image srcFile = ImageIO.read(oldFile);
     int w = srcFile.getWidth(null);
     int h = srcFile.getHeight(null);
     double bili;
     if (width > 0) {
       bili = width / (double) w;
       height = (int) (h * bili);
     } else {
       if (height > 0) {
         bili = height / (double) h;
         width = (int) (w * bili);
       }
     }
     /** 宽,高设定 */
     BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
     tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
     // String filePrex = oldFile.getName().substring(0, oldFile.getName().indexOf('.'));
     /** 压缩后的文件名 */
     // newImage = filePrex + smallIcon+  oldFile.getName().substring(filePrex.length());
     /** 压缩之后临时存放位置 */
     FileOutputStream out = new FileOutputStream(newFile);
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
     JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
     /** 压缩质量 */
     jep.setQuality(quality, true);
     encoder.encode(tag, jep);
     out.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return newFile.getAbsolutePath();
 }
Example #10
0
 /**
  * @see ImageWriter#writeImage(java.awt.image.RenderedImage, java.io.OutputStream,
  *     org.apache.batik.ext.awt.image.spi.ImageWriterParams)
  */
 public void writeImage(RenderedImage image, OutputStream out, ImageWriterParams params)
     throws IOException {
   BufferedImage bi;
   if (image instanceof BufferedImage) {
     bi = (BufferedImage) image;
   } else {
     // TODO Is this the right way?
     bi = GraphicsUtil.makeLinearBufferedImage(image.getWidth(), image.getHeight(), false);
   }
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   if (params != null) {
     JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
     if (params.getJPEGQuality() != null) {
       param.setQuality(
           params.getJPEGQuality().floatValue(), params.getJPEGForceBaseline().booleanValue());
     }
     encoder.encode(bi, param);
   } else {
     encoder.encode(bi);
   }
 }