图片字节转换 文件格式校验

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.imageio.ImageIO;


public class Test {




public static void main(String[] args) throws Exception {
        //图片转字节
byte[] bytes = imageToBytes("e:/jianchu.jpg", "jpg");
System.out.println(bytes.length);
        //字节转图片
ByteArrayInputStream imageStream = new ByteArrayInputStream(bytes);
BufferedImage image = ImageIO.read(imageStream);
// BufferedImage image=ImageIO.read(new File("e:/许女子.jpg"));//
ImageIO.write(image, "jpg", new File("src/test/resources/bb.jpg"));//可以相对路径也可绝对路径
        //校验格式
Test t = new Test();
System.out.println(t.verifyRtf("jpg", "a.JPg"));
Pattern pattern = Pattern.compile(".*\\.(?i)jpg");
Matcher matcher = pattern.matcher("a.Jpg");
boolean b = matcher.matches();
System.out.println(b);


}// bmp, png, jpeg, jpg, gif
    
public static byte[] imageToBytes(String imagePath, String pictRtf) throws IOException {
BufferedImage buffer = ImageIO.read(new File(imagePath));
ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
ImageIO.write(buffer, pictRtf, imageStream);
imageStream.flush();
byte[] bytes = imageStream.toByteArray();
return bytes;
}
/**
* 校验格式
* @param fileRtf
* @param fileFullName
* @return
*/
public boolean verifyRtf(String fileRtf, String fileFullName) {
return Pattern.compile(".*\\.(?i)" + fileRtf).matcher(fileFullName).matches();
}

/**
* imageToBytes

* @param bytes
* @throws IOException
*/
public void bytesToImage(byte[] bytes) throws IOException {
File apple = new File("e:/tes2.jpg");// 把字节数组的图片写到另一个地方
FileOutputStream fos = new FileOutputStream(apple);
fos.write(bytes);
fos.flush();
fos.close();
}


/**
* imageToBytes

* @param imagepath
* @return
*/
public byte[] imageToBytes(String imagepath) {
FileInputStream fs = null;
try {
fs = new FileInputStream(imagepath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] bytes = null;
try {
bytes = new byte[fs.available()];
fs.read(bytes);
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值