图片本质上是一个存储了像素的数组,可以通过改变数组来对图片进行处理,下面是简单地通过图片获取数组的代码
class Image2Buff
{
static byte[] image2Bytes(String imgSrc) throws Exception
{
FileInputStream fin = new FileInputStream(new File(imgSrc));
//可能溢出,简单起见就不考虑太多,如果太大就要另外想办法,比如一次传入固定长度byte[]
byte[] bytes = new byte[fin.available()];
//将文件内容写入字节数组,提供测试的case
fin.read(bytes);
fin.close();
return bytes;
}
}
class Buff2Image
{
/**
@param b 传入的byte
@param tagSrc 目标文件名
*/
static void buff2Image(byte[] b,String tagSrc) throws Exception
{
FileOutputStream fout = new FileOutputStream(tagSrc);
//将字节写入文件
fout.write(b);
fout.close();
}
}
//本质上实现了copy 命令
public class fielzip
{
public static void main(String[] args) throws Exception
{
//先模拟一个图形byte[]
byte[] b = Image2Buff.image2Bytes("D:/test/2.jpg");
//存为文件
Buff2Image.buff2Image(b,"D:/test/3.jpg");
System.out.println("Hello World!");
}
}
上面只是利用图片获取图片的像素信息,下面是对图片中的像素进行处理的代码
public class fielzip {
public static void main(String[] args) {
OutputStream output = null;
try {
BufferedImage img = ImageIO.read(new File("D:/test/src.jpg"));
int imageType = img.getType();
int w = img.getWidth();
int h = img.getHeight();
int startX = 0;
int startY = 0;
int offset = 0;
int scansize = w;
// rgb的数组
int[] rgbArray = new int[offset + (h - startY) * scansize
+ (w - startX)];
img.getRGB(startX, startY, w, h, rgbArray, offset, scansize);
int x0 = w / 2;
int y0 = h / 2;
int rgb = rgbArray[offset + (y0 - startY) * scansize
+ (x0 - startX)];
Color c = new Color(rgb);
System.out.println("中间像素点的rgb:" + c);
// create and save to bmp
File out = new File("D:/test/2.jpg");
if (!out.exists())
out.createNewFile();
output = new FileOutputStream(out);
BufferedImage imgOut = new BufferedImage(w, h, imageType);
imgOut.setRGB(startX, startY, w, h, rgbArray, offset, scansize);
ImageIO.write(imgOut, "bmp", output);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null)
try {
output.close();
} catch (IOException e) {
}
}
}
}