BMP24位格式图片读取

存在很大很大的问题,1.读取后画在面板上的速度太慢;2.有些24位的bmp没发读出来。

先直接贴代码,问题再日后解决。

package com.ct.t20160103;

import java.awt.Color;
import java.awt.Graphics;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import javax.swing.JFrame;

/**
 * @author Chalmers
 * @version 创建时间:2016年1月3日 下午2:00:20
 */
public class BMPTest extends JFrame {

	int image_width = 0;
	int image_height = 0;

	int imageR[][] = null;
	int imageG[][] = null;
	int imageB[][] = null;

	public BMPTest() {

		try {
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}

		this.setBounds(0, 0, image_width, image_height);
		this.setVisible(true);
		setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//		repaint();
	}

	//获得画图所需要的数据
	public void init() throws Exception {
		// 获得图片数据
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				"F://a.bmp"));
		// DataInputStream bis = new DataInputStream(new FileInputStream(
		// "F://a.bmp"));
		// 跳过前面14个字节
		int len = 14;
		byte[] b = new byte[len];
		bis.read(b);

		// 读取40个字节
		len = 40;
		b = new byte[len];
		bis.read(b);

		image_width = ChangeInt(b, 7); // 源图宽度
		image_height = ChangeInt(b, 11); // 源图高度

		showBMPData(bis);
	}

	// 将4个byte类型数据转换成1个int类型
	public int ChangeInt(byte[] bi, int start) {
		return (((int) bi[start] & 0xff) << 24)
				| (((int) bi[start - 1] & 0xff) << 16)
				| (((int) bi[start - 2] & 0xff) << 8) | (int) bi[start - 3]
				& 0xff;
	}

	//获得图片中每一个像素点的数据
	//每一个像素点又三个byte类型数据组成,分别读取出来
	public void showBMPData(BufferedInputStream bis) throws IOException {
		//图片有多大,则构造多大的数组
		imageR = new int[image_width][image_height];
		imageG = new int[image_width][image_height];
		imageB = new int[image_width][image_height];

		//判断图片数据最后是否补0
		int skip_width = 0;
		if (!(image_width * 3 % 4 == 0)) {
			skip_width = 4 - image_width * 3 % 4;
		}

		//读取图片的每一个像素中的颜色的数据
		for (int h = image_height - 1; h >= 0; h--) {
			//要按顺序读取
			for (int w = 0; w < image_width; w++) {
				int b = bis.read();
				int g = bis.read();
				int r = bis.read();

				//将数据存放进数组
				imageR[h][w] = r;
				imageG[h][w] = g;
				imageB[h][w] = b;
				
				if (w == 0) {
					bis.skip(skip_width);
				}
			}
		}
	}

	@Override
	public void paint(Graphics g) {
		//在画图这个地方是很有问题,它是一个像素点一个像素点的画,导致速度很慢
		//待修改
		for (int i = 0; i < image_width; i++) {
			for (int j = 0; j < image_height; j++) {
				g.setColor(new Color(imageR[i][j], imageG[i][j], imageB[i][j]));
				g.fillOval(j, i, 1, 1);
			}
		}
	}

	public static void main(String[] args) throws Exception {

		new BMPTest();
	}
}

猜你喜欢

转载自moonmonster.iteye.com/blog/2270394