Exemplo n.º 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;
 }
Exemplo n.º 2
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();
      }
    }
  }
Exemplo n.º 3
0
  /**
   * 把图片印刷到图片上
   *
   * @param pressImg -- 水印文件
   * @param targetImg -- 目标文件
   * @param x
   * @param y
   */
  public static final void pressImage(String pressImg, String targetImg, int x, int y) {
    try {
      File _file = new File(targetImg);
      Image src = ImageIO.read(_file);
      int wideth = src.getWidth(null);
      int height = src.getHeight(null);
      BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
      Graphics g = image.createGraphics();
      g.drawImage(src, 0, 0, wideth, height, null);

      // 水印文件
      File _filebiao = new File(pressImg);
      Image src_biao = ImageIO.read(_filebiao);
      int wideth_biao = src_biao.getWidth(null);
      int height_biao = src_biao.getHeight(null);
      g.drawImage(
          src_biao,
          wideth - wideth_biao - x,
          height - height_biao - y,
          wideth_biao,
          height_biao,
          null);
      // /
      g.dispose();
      FileOutputStream out = new FileOutputStream(targetImg);
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      encoder.encode(image);
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 4
0
 /**
  * 将比较大的图片按比例缩小图片 例如几M的图片刚将缩小为宽度为1024的图片缩小后大概只有几百K
  *
  * @param in 图片的输入流
  * @param imgName 图片的名称
  * @param dir 存放的路径
  * @return
  */
 public static boolean zoomOut(InputStream in, String imgName, String dir) {
   boolean zoom = false;
   int new_w, new_h;
   File file = new File(dir + "\\" + imgName);
   try {
     if (!file.exists()) { // 如果文件不存在,则创建新的空文件
       file.createNewFile();
     }
     BufferedImage image = ImageIO.read(in);
     int width = image.getWidth();
     int height = image.getHeight();
     new_w = width;
     new_h = height;
     if (width > Constants.MAX_WIDTH) { // 按比例缩小图片
       new_w = Constants.MAX_WIDTH;
       new_h = new_w * height / width;
     }
     BufferedImage result = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
     Graphics gs = result.createGraphics();
     gs.drawImage(image, 0, 0, new_w, new_h, null);
     gs.dispose();
     FileOutputStream out = new FileOutputStream(file);
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
     encoder.encode(result);
     out.close();
   } catch (IOException e) {
     Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, e);
   }
   return zoom;
 }
  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");
    }
  }
Exemplo n.º 6
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();
    }
  }
Exemplo n.º 7
0
  /**
   * 打印文字水印图片
   *
   * @param pressText --文字
   * @param targetImg -- 目标图片
   * @param fontName -- 字体名
   * @param fontStyle -- 字体样式
   * @param color -- 字体颜色
   * @param fontSize -- 字体大小
   * @param x -- 偏移量
   * @param y
   */
  public static void pressText(
      String pressText,
      String targetImg,
      String fontName,
      int fontStyle,
      int color,
      int fontSize,
      int x,
      int y) {
    try {
      File _file = new File(targetImg);
      Image src = ImageIO.read(_file);
      int wideth = src.getWidth(null);
      int height = src.getHeight(null);
      BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
      Graphics g = image.createGraphics();
      g.drawImage(src, 0, 0, wideth, height, null);
      // String s="www.qhd.com.cn";
      g.setColor(Color.RED);
      g.setFont(new Font(fontName, fontStyle, fontSize));

      g.drawString(pressText, wideth - fontSize - x, height - fontSize / 2 - y);
      g.dispose();
      FileOutputStream out = new FileOutputStream(targetImg);
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      encoder.encode(image);
      out.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Exemplo n.º 8
0
  /*
   * Retrieve the JPEGDecodeParam object for the indicated table. If the
   * object is available in the config, use it; otherwise retrieve it from
   * the server. An ArrayIndexOutOfBoundsException will be thrown if
   * the parameter is not in the range [1,256].
   */
  private synchronized JPEGDecodeParam getJPEGDecodeParam(int tableIndex) {
    JPEGDecodeParam decodeParam = decodeParamCache[tableIndex - 1];

    if (decodeParam == null) {
      String cmd = new String("OBJ=Comp-group," + TILE_JPEG + "," + tableIndex);
      InputStream stream = postCommands(new String[] {cmd});
      String label = null;
      while ((label = getLabel(stream)) != null) {
        if (label.startsWith("comp-group")) {
          byte[] table = getDataAsByteArray(stream);
          ByteArrayInputStream tableStream = new ByteArrayInputStream(table);
          JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(tableStream);
          try {
            // This call is necessary.
            decoder.decodeAsRaster();
          } catch (Exception e) {
            // Ignore.
          }
          decodeParam = decoder.getJPEGDecodeParam();
        } else {
          checkError(label, stream, true);
        }
      }

      endResponse(stream);

      if (decodeParam != null) {
        decodeParamCache[tableIndex - 1] = decodeParam;
      }
    }

    return decodeParam;
  }
Exemplo n.º 9
0
 private void getVerifyImage(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   response.setContentType("image/jpeg");
   OutputStream out = response.getOutputStream();
   int width = 46;
   int height = 18;
   int length = 4;
   boolean useCharacter = false;
   try {
     width = Integer.parseInt((String) request.getParameter("w"));
   } catch (Exception ex) {
   }
   try {
     height = Integer.parseInt((String) request.getParameter("h"));
   } catch (Exception ex) {
   }
   try {
     length = Integer.parseInt((String) request.getParameter("l"));
   } catch (Exception ex) {
   }
   try {
     useCharacter = Boolean.valueOf((String) request.getParameter("uc"));
   } catch (Exception ex) {
   }
   // System.out.println(useCharacter);
   List list = StringUtil.getVerifyImage(width, height, length, useCharacter);
   request.getSession().setAttribute("verifyCode", (String) list.get(0));
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   encoder.encode((BufferedImage) list.get(1));
   out.close();
 }
Exemplo n.º 10
0
    @SuppressWarnings("restriction")
    public static TCImageDocument create(
        TCObject tc, MimeType mimeType, String filename, InputStream in, String description)
        throws Exception {

      mimeType = checkMimeType(mimeType);

      ByteArrayOutputStream out = null;

      try {
        BufferedImage image = null;

        if (MimeType.ImageJPEG.equals(mimeType)) {
          try {
            com.sun.image.codec.jpeg.JPEGImageDecoder decoder =
                com.sun.image.codec.jpeg.JPEGCodec.createJPEGDecoder(in);
            image = decoder.decodeAsBufferedImage();
          } catch (Exception e) {
            log.warn(null, e);
          }
        }

        if (image == null) {
          image = ImageIO.read(in);
        }

        TCReferencedInstance ref =
            createReferencedInstance(
                tc, UID.MultiFrameTrueColorSecondaryCaptureImageStorage, MODALITY);

        DicomObject metaData =
            TCDocumentObject.createDicomMetaData(
                mimeType,
                filename,
                description,
                ref,
                tc.getPatientId(),
                tc.getPatientIdIssuer(),
                tc.getPatientName(),
                MODALITY);

        metaData.putInt(Tag.NumberOfFrames, VR.IS, 1);

        return new TCImageDocument(mimeType, ref, metaData, image);
      } finally {
        if (in != null) {
          try {
            in.close();
          } catch (Exception e) {
          }
        }
        if (out != null) {
          try {
            out.close();
          } catch (Exception e) {
          }
        }
      }
    }
Exemplo n.º 11
0
 public void genJjtImg(ASTStart n) {
   try {
     addNodeToImg(n, 1000, 10);
     FileOutputStream fos = new FileOutputStream("src\\img.jpg");
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
     encoder.encode(bufImage);
   } catch (Exception e) {
   }
 }
Exemplo n.º 12
0
 // public static Date getNextDate(Date d){
 // return getAfterDaysDate(d,1);
 // }
 //
 // public static Date getAfterDaysDate(Date d, int days){
 // long addTime = 1;
 // addTime *= days;
 // addTime *= 24;
 // addTime *= 60;
 // addTime *= 60;
 // addTime *= 1000;
 // addTime -= 1;
 // return new Date(d.getTime() + addTime);
 // }
 public static void writeImage(InputStream in, OutputStream out) throws Exception {
   Image src = ImageIO.read(in); // ����Image����
   int h = src.getHeight(null);
   int w = src.getWidth(null);
   BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
   tag.getGraphics().drawImage(src, 0, 0, w, h, null); // ����������?
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   encoder.encode(tag); // ��JPEG����
 }
  /**
   * 调用该方法将得到的验证码生成图象
   *
   * @param sCode 验证码
   * @return
   */
  private void createImage(String sCode) throws Throwable {
    this.response.setContentType("image/jpeg");
    // 设置页面不缓存
    this.response.setHeader("Pragma", "No-cache");
    this.response.setHeader("Cache-Control", "no-cache");
    this.response.setDateHeader("Expires", 0);
    // 图象宽度与高度
    int width = 15 * this.codeLength;
    int 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));

    // 画边框
    // g.setColor(new Color());
    // g.drawRect(0,0,width-1,height-1)

    // 随机产生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);
    }

    for (int i = 0; i < this.codeLength; i++) {
      String rand = sCode.substring(i, i + 1);
      // 将认证码显示到图象中
      g.setColor(
          new Color(20 + random.nextInt(60), 20 + random.nextInt(120), 20 + random.nextInt(180)));
      g.drawString(rand, 13 * i + 6, 16);
    }
    // 图象生效
    g.dispose();
    this.request.getSession().setAttribute("rand", sCode);
    ServletOutputStream outStream = null;
    try {
      outStream = response.getOutputStream();
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
      encoder.encode(image);
    } finally {
      if (outStream != null) outStream.close();
    }
  }
Exemplo n.º 14
0
  /**
   * @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");
    }
  }
Exemplo n.º 15
0
  public void setNombreArchivoImagen(String nombreArchivoImagen) {
    this.nombreArchivoImagen = nombreArchivoImagen;
    InputStream in = getClass().getResourceAsStream(this.nombreArchivoImagen);
    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
    try {
      this.imagen = decoder.decodeAsBufferedImage();
      in.close();
    } catch (Exception ex) {

    }
  }
 public void saveImage(ByteBuffer bb, String filename) throws ImageFormatException, IOException {
   ByteArrayInputStream bais = new ByteArrayInputStream(bb.array());
   JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(bais);
   //	    BufferedImage image = decoder.decodeAsBufferedImage();
   //	    BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(new
   // File(filename)));
   //	    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bf);
   //	    encoder.encode(image);
   //	    bf.flush();
   //	    bf.close();
 }
Exemplo n.º 17
0
 /**
  * 生成图片
  *
  * @param fileLocation
  */
 public void createImage(String fileLocation) {
   try {
     FileOutputStream fos = new FileOutputStream(fileLocation);
     BufferedOutputStream bos = new BufferedOutputStream(fos);
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
     encoder.encode(image);
     bos.close();
   } catch (Exception e) {
     System.out.println(e);
   }
 }
Exemplo n.º 18
0
  private BufferedImage readBufferedImageJpegCompression(DataInput in) throws IOException {
    int size = in.readInt();
    byte[] buffer = new byte[size];
    in.readFully(buffer);
    ByteArrayInputStream byteStream = new ByteArrayInputStream(buffer);

    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(byteStream);
    byteStream.close();

    return decoder.decodeAsBufferedImage();
  }
Exemplo n.º 19
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();
 }
Exemplo n.º 20
0
  private void writeBufferedImageJpegCompression(DataOutput out, BufferedImage image)
      throws IOException {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(byteStream);

    encoder.encode(image);
    byteStream.close();

    byte[] buffer = byteStream.toByteArray();
    out.writeInt(buffer.length);
    out.write(buffer);
  }
Exemplo n.º 21
0
  public static void ImageScale(String sourceImg, String targetImg, int width, int height) {
    try {
      Image image = javax.imageio.ImageIO.read(new File(sourceImg));
      int imageWidth = image.getWidth(null);
      int imageHeight = image.getHeight(null);
      float scale = getRatio(imageWidth, imageHeight, width, height);
      imageWidth = (int) (scale * imageWidth);
      imageHeight = (int) (scale * imageHeight);

      image = image.getScaledInstance(imageWidth, imageHeight, Image.SCALE_AREA_AVERAGING);
      // Make a BufferedImage from the Image.
      BufferedImage mBufferedImage =
          new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = mBufferedImage.createGraphics();

      // Map readeringHint = new HashMap();
      // readeringHint.put(RenderingHints.KEY_ALPHA_INTERPOLATION,
      // RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
      // readeringHint.put(RenderingHints.KEY_ANTIALIASING,
      // RenderingHints.VALUE_ANTIALIAS_ON);
      // readeringHint.put(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
      // readeringHint.put(RenderingHints.KEY_DITHERING,
      // RenderingHints.VALUE_DITHER_ENABLE);
      // readeringHint.put(RenderingHints.KEY_INTERPOLATION,
      // RenderingHints.VALUE_INTERPOLATION_BILINEAR);//VALUE_INTERPOLATION_BICUBIC
      // readeringHint.put(RenderingHints.KEY_RENDERING,
      // RenderingHints.VALUE_RENDER_QUALITY);
      // g.setRenderingHints(readeringHint);

      g2.drawImage(image, 0, 0, imageWidth, imageHeight, Color.white, null);
      g2.dispose();

      float[] kernelData2 = {
        -0.125f, -0.125f, -0.125f, -0.125f, 2, -0.125f, -0.125f, -0.125f, -0.125f
      };
      Kernel kernel = new Kernel(3, 3, kernelData2);
      ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
      mBufferedImage = cOp.filter(mBufferedImage, null);
      FileOutputStream out = new FileOutputStream(targetImg);
      // JPEGEncodeParam param =
      // encoder.getDefaultJPEGEncodeParam(bufferedImage);
      // param.setQuality(0.9f, true);
      // encoder.setJPEGEncodeParam(param);
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      encoder.encode(mBufferedImage);
      out.close();
    } catch (FileNotFoundException fnf) {
    } catch (IOException ioe) {
    } finally {

    }
  }
Exemplo n.º 22
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());
   }
 }
Exemplo n.º 23
0
  /*
   * Create a Raster from a JPEG-compressed data stream.
   */
  private Raster getJPEGTile(int tx, int ty, int subType, byte[] data) {
    int tableIndex = (subType >> 24) & 0x000000ff;
    ;
    boolean colorConversion = (subType & 0x00ff0000) != 0;
    JPEGDecodeParam decodeParam = null;
    if (tableIndex != 0) {
      decodeParam = getJPEGDecodeParam(tableIndex);
    }

    ByteArrayInputStream byteStream = new ByteArrayInputStream(data);
    JPEGImageDecoder decoder =
        decodeParam == null
            ? JPEGCodec.createJPEGDecoder(byteStream)
            : JPEGCodec.createJPEGDecoder(byteStream, decodeParam);

    Raster raster = null;
    try {
      raster = decoder.decodeAsRaster().createTranslatedChild(tx, ty);
    } catch (Exception e) {

      ImagingListener listener = ImageUtil.getImagingListener(renderHints);
      listener.errorOccurred(
          JaiI18N.getString("IIPResolutionOpImage3"), new ImagingException(e), this, false);
      /*
                  String msg = JaiI18N.getString("IIPResolutionOpImage3")+" "+
                      e.getMessage();
                  throw new RuntimeException(msg);
      */
    }
    closeStream(byteStream);

    if (colorSpaceType == CS_NIFRGB && colorConversion) {
      YCbCrToNIFRGB(raster);
    }

    return raster;
  }
Exemplo n.º 24
0
 private void write(JComponent myComponent, OutputStream out) throws Exception {
   int imgWidth = (int) myComponent.getSize().getWidth(),
       imgHeight = (int) myComponent.getSize().getHeight();
   Dimension size = new Dimension(imgWidth, imgHeight);
   BufferedImage myImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
   Graphics2D g2 = myImage.createGraphics();
   myComponent.paint(g2);
   try {
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
     encoder.encode(myImage);
     out.close();
   } catch (Exception e) {
     throw new Exception("GRAPHICS ERROR,CANNOT CREATE JPEG FORMAT");
   }
 }
Exemplo n.º 25
0
  // 图片处理
  public String compressPic() {
    try {
      // 获得源文件
      file = new File(inputDir + inputFileName);
      if (!file.exists()) {
        return "";
      }
      Image img = ImageIO.read(file);
      // 判断图片格式是否正确
      if (img.getWidth(null) == -1) {
        System.out.println(" can't read,retry!" + "<BR>");
        return "no";
      } else {
        int newWidth;
        int newHeight;
        // 判断是否是等比缩放
        if (this.proportion == true) {
          // 为等比缩放计算输出的图片宽度及高度
          double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
          double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
          // 根据缩放比率大的进行缩放控制
          double rate = rate1 > rate2 ? rate1 : rate2;
          newWidth = (int) (((double) img.getWidth(null)) / rate);
          newHeight = (int) (((double) img.getHeight(null)) / rate);
        } else {
          newWidth = outputWidth; // 输出的图片宽度
          newHeight = outputHeight; // 输出的图片高度
        }
        BufferedImage tag =
            new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);

        /*
         * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
         */
        tag.getGraphics()
            .drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
        System.out.println(outputDir + outputFileName);
        FileOutputStream out = new FileOutputStream(outputDir + outputFileName);
        // JPEGImageEncoder可适用于其他图片类型的转换
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(tag);
        out.close();
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return "ok";
  }
Exemplo n.º 26
0
  /**
   * Write to <code>fn</code> file the <code>data</code> using the <code>width, height</code>
   * variables. Data is assumed to be 8bit RGB.
   *
   * @throws FileNotFoundException if the directory/image specified is wrong
   * @throws IOException if there are problems reading the file.
   */
  public static void writeImage(String fn, byte[] data, int width, int height)
      throws FileNotFoundException, IOException {

    FileOutputStream fOut = new FileOutputStream(fn);
    JPEGImageEncoder jpeg_encode = JPEGCodec.createJPEGEncoder(fOut);

    int ints[] = new int[data.length];
    for (int i = 0; i < data.length; i++)
      ints[i] = 255 << 24 | (data[i] & 0xff) << 16 | (data[i] & 0xff) << 8 | (data[i] & 0xff);

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    image.setRGB(0, 0, width, height, ints, 0, width);

    jpeg_encode.encode(image);
    fOut.close();
  }
Exemplo n.º 27
0
  // 写jpg等图片
  private static BufferedImage writeOtherImage(
      Image image, int newWidth, int newHeight, String filePath) {

    BufferedImage newImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
    newImage
        .getGraphics()
        .drawImage(image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
    try {
      FileOutputStream outStream = new FileOutputStream(filePath);
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
      encoder.encode(newImage);
      outStream.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return newImage;
  }
Exemplo n.º 28
0
 // read a jpeg file into a buffered image
 protected static Image loadJPG(String filename) {
   FileInputStream in = null;
   try {
     in = new FileInputStream(filename);
   } catch (java.io.FileNotFoundException io) {
     System.out.println("File Not Found");
   }
   JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
   BufferedImage bi = null;
   try {
     bi = decoder.decodeAsBufferedImage();
     in.close();
   } catch (java.io.IOException io) {
     System.out.println("IOException");
   }
   return bi;
 }
Exemplo n.º 29
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");
   }
 }
Exemplo n.º 30
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);
 }