Example #1
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();
    }
  }
Example #2
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();
 }
Example #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();
    }
  }
Example #4
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 #5
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;
 }
Example #6
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);
    }
  }
  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");
    }
  }
Example #8
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();
    }
  }
Example #10
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) {
   }
 }
  /**
   * @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 #12
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);
   }
 }
  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);
  }
Example #14
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 {

    }
  }
Example #15
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 #16
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 #17
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");
   }
 }
Example #18
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";
  }
Example #19
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();
  }
Example #20
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;
  }
Example #21
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 #22
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);
 }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("image/jpeg");
    ServletOutputStream out = response.getOutputStream();

    int width = 60;
    int height = 20;
    BufferedImage image = new BufferedImage(width, height, 1);

    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", 0, 18));

    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);
    }

    String rand = RandomStringUtils.random(4, true, true);

    for (int i = 0; i < 4; ++i) {
      char c = rand.charAt(i);
      g.setColor(
          new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));

      g.drawString(String.valueOf(c), 13 * i + 6, 16);
    }
    HttpSession seesion = request.getSession();
    seesion.setAttribute("check_code", rand);

    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(image);
    out.close();
  }
Example #24
0
 /**
  * 输出地图
  *
  * @param src_zq 参数
  * @param src_zy 参数
  * @param ctx 参数
  */
 public static void getExportMapImg(String src_zq, String src_zy, String ctx) {
   try {
     URL url_zq = new URL(src_zq);
     BufferedImage bi_zq = ImageIO.read(url_zq);
     URL url_zy = new URL(src_zy);
     BufferedImage bi_zy = ImageIO.read(url_zy);
     int width = bi_zq.getWidth();
     int height = bi_zq.getHeight();
     Graphics2D graphics = bi_zq.createGraphics();
     graphics.drawImage(bi_zq, 0, 0, width, height, null);
     graphics.drawImage(bi_zy, 0, 0, width, height, null);
     graphics.dispose();
     FileOutputStream out = new FileOutputStream("D:\\" + new Date().getTime() + ".png");
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
     // 绘制新的文件
     encoder.encode(bi_zq);
     out.close();
   } catch (Exception ex) {
   }
 }
Example #25
0
  public static void writeImage(InputStream in, OutputStream out, int maxWidth, int maxHeight) {
    try {
      Image src = ImageIO.read(in); // ����Image����
      int h = src.getHeight(null);
      int w = src.getWidth(null);
      // case 1
      if (h <= maxHeight && w <= maxWidth) {

      }
      // case 2
      else if (h > maxHeight && w <= maxWidth) {
        h = maxHeight;
        w = h * (maxWidth / maxHeight);
      }
      // case 3
      else if (h <= maxHeight && w > maxWidth) {
        w = maxWidth;
        h = w * maxHeight / maxWidth;
      }
      // case 4
      else if (h > maxHeight && w > maxWidth) {
        if (h / maxHeight > w / maxWidth) {
          w = w * maxHeight / h;
          h = maxHeight;
        } else {
          h = h * maxWidth / w;
          w = maxWidth;
        }
      }
      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����
    } catch (ImageFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #26
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 #27
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);
   }
 }
Example #28
0
  public void saveMinPhoto(String srcURL, String deskURL, double comBase, double scale)
      throws Exception {
    /*srcURl 原图地址;deskURL 缩略图地址;comBase 压缩基数;scale 压缩限制(宽/高)比例*/
    java.io.File srcFile = new java.io.File(srcURL);
    Image src = javax.imageio.ImageIO.read(srcFile);
    int srcHeight = src.getHeight(null);
    int srcWidth = src.getWidth(null);
    int deskHeight = 0; // 缩略图高
    int deskWidth = 0; // 缩略图宽
    double srcScale = (double) srcHeight / srcWidth;
    if (srcHeight > comBase || srcWidth > comBase) {
      if (srcScale >= scale || 1 / srcScale > scale) {
        if (srcScale >= scale) {
          deskHeight = (int) comBase;
          deskWidth = srcWidth * deskHeight / srcHeight;
        } else {
          deskWidth = (int) comBase;
          deskHeight = srcHeight * deskWidth / srcWidth;
        }

      } else if (srcHeight > comBase) {
        deskHeight = (int) comBase;
        deskWidth = srcWidth * deskHeight / srcHeight;
      } else {
        deskWidth = (int) comBase;
        deskHeight = srcHeight * deskWidth / srcWidth;
      }
    } else {
      deskHeight = srcHeight;
      deskWidth = srcWidth;
    }
    BufferedImage tag = new BufferedImage(deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR);
    tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeight, null); // 绘制缩小后的图
    FileOutputStream deskImage = new FileOutputStream(deskURL); // 输出到文件流
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(deskImage);
    encoder.encode(tag); // 近JPEG编码
    deskImage.close();
  }
Example #29
0
 /**
  * 缩放图像(按高度和宽度缩放)
  *
  * @param srcImageFile 源图像文件地址
  * @param result 缩放后的图像地址
  * @param height 缩放后的高度
  * @param width 缩放后的宽度
  * @param bb 比例不对时是否需要补白:true为补白; false为不补白;
  */
 public static final void scaleGIF(
     String srcImageFile, String result, int height, int width, boolean bb) {
   try {
     double ratiox = 0.0; // 缩放比例
     double ratioy = 0.0; // 缩放比例
     File f = new File(srcImageFile);
     BufferedImage bi = ImageIO.read(f);
     // Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
     Image itemp = javax.imageio.ImageIO.read(f);
     int imgwidth = bi.getWidth();
     int imgheight = bi.getHeight();
     int newheight = imgheight;
     int newwidth = imgwidth;
     // 以比例小的为基准
     if (imgwidth / width > imgheight / height) { // 以height为基准
       newheight = height;
       newwidth = imgwidth * height / imgheight;
       ratioy = (new Integer(height)).doubleValue() / bi.getHeight();
       ratiox = ratioy;
     } else { // 以width为基准
       newwidth = width;
       newheight = imgheight * width / imgwidth;
       ratiox = (new Integer(width)).doubleValue() / bi.getWidth();
       ratioy = ratiox;
     }
     BufferedImage tag = new BufferedImage(newwidth, newheight, BufferedImage.TYPE_INT_RGB);
     tag.getGraphics()
         .drawImage(itemp.getScaledInstance(newwidth, newheight, Image.SCALE_SMOOTH), 0, 0, null);
     FileOutputStream out = new FileOutputStream(result);
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
     encoder.encode(tag);
     out.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #30
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    HttpSession session = req.getSession(false);

    //	设置页面不缓存
    res.setContentType("image/jpeg");
    res.setHeader("Pragma", "No-cache");
    res.setHeader("Cache-Control", "no-cache");
    res.setDateHeader("Expires", 0);

    //	 在内存中创建图象
    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 < 200; 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);
    }

    //	 取随机产生的认证码(4位数字加字母)
    String sRand = "";
    for (int i = 0; i < 4; i++) {
      String rand = getRandStr();
      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
    session.setAttribute("rand", sRand);

    //	 图象生效
    g.dispose();

    //	 输出图象到页面
    // ImageIO.write(image, "JPEG", res.getOutputStream());
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(res.getOutputStream());
    encoder.encode(image);
  }