关于BufferedImage编辑图片的问题

08-08-29 wq8987
我下面的代码执行后,所载的图是个黑的,不过字可以显示

Java code

package test_img;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

import java.io.File;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGImageEncoder;

import sun.awt.image.ToolkitImage;

class GuiCamera

{

private String fileName; // 文件的前缀

private String defaultName = "GuiCamera";

static int serialNum = 0;

private String imageFormat; // 图像文件的格式

private String defaultImageFormat = "jpg";

// Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

public GuiCamera()

{

fileName = defaultName;

imageFormat = defaultImageFormat;

}

/***********************************************************************

* @param s

* the surname of the snapshot file

* @param format

* the format of the image file, it can be "jpg" or "png"

* 本构造支持JPG和PNG文件的存储

**********************************************************************/

public GuiCamera(String s, String format)

{

fileName = s;

imageFormat = format;

}

public void snapShot()

{

try

{

Toolkit tk = Toolkit.getDefaultToolkit();

Image img = tk.getImage(GuiCamera.class.getClassLoader().getResource("img\\demo1.jpg"));

BufferedImage screenshot = new BufferedImage(480,360,BufferedImage.TYPE_3BYTE_BGR);

Graphics g = screenshot.getGraphics();

g.drawOval(20, 20, 20, 20);

g.drawImage(img, 0,0, null);

g.drawString("cut image", 50, 50);

screenshot = screenshot.getSubimage(0, 0, 400, 300);

g.dispose();

screenshot.flush();

serialNum++;

// 根据文件前缀变量和文件格式变量,自动生成文件名

String name = fileName + String.valueOf(serialNum) + "."

+ imageFormat;

File f = new File(name);

System.out.print("Save File " + name);

// 将screenshot对象写入图像文件

ImageIO.write(screenshot, imageFormat, f);

System.out.print("..Finished! ");

} catch (Exception ex)

{

System.out.println(ex);

}

}

public static void main(String[] args)

{

GuiCamera cam = new GuiCamera("Test", "jpg");

cam.snapShot();

}

}

banq
2008-08-29 17:09
使用IDE 自己断点调试,一条语句一条语句测试,查看状态。

wq8987
2008-08-30 16:24
那个IMG可以找到,可是它就是个黑的,写不到BufferedImage里面去,不知道哦什么!

freebox
2008-08-30 17:59
获取jpg图片源有问题

替换下面两行

Toolkit tk = Toolkit.getDefaultToolkit();

Image img = tk.getImage(GuiCamera.class.getClassLoader().getResource("img\\demo1.jpg"));

Image img = ImageIO.read(GuiCamera.class.getResource("img\\demo1.jpg"));

猜你喜欢