实现一个功能 上传一张只是JPG 格式的图片,上传后保存到一个文件夹里面。直接存储成3种大小格式 例如:30x30 50x50 80x80 这种! 求大神解答!

解决方案 »

  1.   

    算了直接发吧! public static boolean compressPic(byte[] arr, String path, String name, File dst, int width, int height,
    boolean isScale) {
    // 图片流
    InputStream bufin = new ByteArrayInputStream(arr);
    FileOutputStream out = null;
    boolean b = false;
    try {
    // 图片流
    BufferedImage img = ImageIO.read(bufin);
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);
    if ((srcHeight > height) || (srcWidth > width)) {
    // 判断是否是等比缩放
    if (isScale) {
    double rate = Math.max((double) srcWidth / width, (double) srcHeight / height);
    width = (int) (srcWidth / rate);
    height = (int) (srcHeight / rate);
    }
    BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Image image = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
    tag.getGraphics().drawImage(image, 0, 0, null);
    out = new FileOutputStream(dst);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(tag);
    out.flush();
    } else {
    saveImage(dst, arr, path, name);
    }
    b = true;
    } catch (IOException e) {
    e.printStackTrace();
    }
    return b;
    }
      

  2.   

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    FileInputStream fis = (FileInputStream) inputStream;
    int len = 0;
    byte[] b = new byte[BUFFER_SIZE];
    while ((len = fis.read(b)) != -1) {
    bos.write(b, 0, len);
    }
    byte[] byteArr = bos.toByteArray();
    saveImage(realImageFile, byteArr, path, realRelative); // 原图保存
    compressPic(byteArr, path, relative, imageFile, 400, 300);// 大图,放大保存
    compressPic(byteArr, path, smallRelative, smllImageFile, 180, 120);// 小图,缩小保存