java中图片简单操作

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">最近做网站时,经常会对图片进行操作,用到的基本操作如下:</span>

1.读取图片到 二进制数组中

        ByteArrayOutputStream out = null ;
        BufferedInputStream in = null;
        File file = new File(relativePath);
        in = new BufferedInputStream(new FileInputStream(file));
        out = new ByteArrayOutputStream((int)file.length());
        byte[] buffer = new byte[1024];
        int len = 0; 
        while ((len = in.read(buffer, 0, buffer.length)) != - 1) {
            out.write(buffer, 0, len);
        }
        in.close();          
        byte[] blob= out.toByteArray();      

ByteArrayOutputStream 的flush和close都做的空操作,所以没必要写上去。

2.二进制数据到写入图片

    public static String saveFile(String path, byte[] blob) {
        if(blob == null) {
            return null;
        }

        File file = new File(TheApp.getRootPath(path));
        if (file.exists()) {
            return null;
        }

        // 创建父目录
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
            if (!file.getParentFile().exists()) {
                logger.error("创建文件目录失败!");
                return null;
            }
        }
        // 写数据
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(blob);
            out.flush();
        }
        catch (Exception e) {
            logger.error("写文件失败:" + path);
            file.delete();
            return null;
        }
        finally {
            close(out);
        }
        return path.toString();
    }

3.图片传输

图片传输 用的是base64数据格式

用到的org.apache.xerces.impl.dv.util里面的Base64.encode()和Base64.decode();

4.图片压缩

对于比较大的图片 保存之前需要等比例 缩小下

  ByteArrayInputStream in= new ByteArrayInputStream(blob);
                    BufferedImage bufferImage = ImageIO.read(in);     //将in作为输入流,读取图片存入image中,而这里in可以为ByteArrayInputStream();
                    Image srcImg  =(Image) bufferImage ;//取源图
                    int  width  =  100; //假设要缩小到100点像素
                    int  height =  srcImg.getHeight(null)*100/srcImg.getWidth(null);//按比例,将高度缩减
                    Image smallImg =srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH);//缩小
                    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
                    Graphics g = bi.getGraphics();
                    g.drawImage(smallImg, 0, 0, null);
                    ByteArrayOutputStream newByte=new ByteArrayOutputStream();
                    ImageIO.write(bi,"jpg",newByte);
                    byte[] out=newByte.toByteArray();

5.图片网页显示

传输时,传输的是一个相对路径

网页中用img.src 接收即可

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值