工具类:
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageIOUtils {
public static byte[] read(String name) throws IOException {
File file = new File(name);
if (!file.exists() || !file.isFile())
return null;
FileInputStream fis = new FileInputStream(name);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 1];
for (int length = fis.read(buffer); length > 0; length = fis.read(buffer))
baos.write(buffer, 0, length);
baos.flush();
byte[] bytes = baos.toByteArray();
close(baos);
close(fis);
return bytes;
}
public static void write(byte[] data, String name) throws IOException {
FileOutputStream fos = new FileOutputStream(name);
fos.write(data);
fos.flush();
close(fos);
}
public static void close(Closeable closeable) {
if (closeable == null)
return;
try {
closeable.close();
} catch (IOException e) {
}
}
}
测试类:
import java.io.IOException;
import com.mk.util.ImageIOUtils;
public class ImageIOUtilsTests {
public static void main(String[] args) throws IOException {
byte[] data = ImageIOUtils.read("E:/PrtSc/1/starry-sky.jpg"); // Read from
ImageIOUtils.write(data, "E:/PrtSc/1/starry-sky-copy.jpg"); // Write to
}
}