java中保存BufferedImage时一片黑色,img获取大小时老是返回-1

wangzhichao_king wangzhichao_king 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

如题目所示,我运行以下代码后,在方法三中可以正常显示jpg图片,但是方法一和方法二当中下载下来的JPG图片打开后却是只有一个黑色的矩形块,但是大小和原图一样。返回的console信息我已经添加在源码后面,请各位高手不吝赐教。。。在此先行感谢了。

import java.awt.AWTEvent;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ImageProducer;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.imageio.ImageIO;

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



public class CopyOfTest extends Frame{

public String url = "http://t1.baidu.com/it/u=3426770779,3149920518&fm=0&gp=-36.jpg";
public String filePath = "d:\\";
public String fileType = "JPEG";
public String fileName = "Test.jpg";
public Image img = null;

public void paint(Graphics g){//画出jpg
g.drawImage(img, 20, 20,this);
}

public void processWindowEvent(WindowEvent e){//关闭
super.processWindowEvent(e);
if(e.getID()==WindowEvent.WINDOW_CLOSING)
System.exit(0);
}



public static void main(String[] args) {//测试主程序
CopyOfTest t =new CopyOfTest();

try {
URL url = new URL (t.url);//建立HttpURLConnetion连接并获得相关内容信息
HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
int nLen = httpConn.getContentLength();
String sType = httpConn.getContentType();
Object oContent = httpConn.getContent();
System.out.println(nLen + " "+sType + " " + oContent);//打印jpg文件总长度+类型+对象号

Toolkit tk=Toolkit.getDefaultToolkit(); //将下载内容转换成Image格式的文件
Image img = tk.createImage((ImageProducer) oContent);

int nWidth = img.getWidth(null);//获取img的大小
int nHeight = img.getHeight(null);
System.out.println(nWidth + " " + nHeight);//打印image文件的大小,但是这里老是返回-1,我的网络绝无问题

BufferedImage bimg = new BufferedImage(139,95,BufferedImage.TYPE_INT_RGB);//这里的139*95是我用IE看到的图片属性

//方法一:encode(bimg),得到图片test.jpg,用很多工具打开过,只有一个黑色矩形块
FileOutputStream ou = new FileOutputStream(new File(t.filePath+File.separator+t.fileName));
BufferedOutputStream bf = new BufferedOutputStream(ou);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bf);
encoder.encode(bimg);
bf.flush();
bf.close();

//方法二:用ImageIO直接输出bimg,得到图片io.jpg,用很多工具打开过,只有一个黑色矩形块
ImageIO.write(bimg, t.fileType, new File(t.filePath+"//io."+t.fileType));

//方法三:用frame打开,正常显示出图片
t.img = img;
t.enableEvents(AWTEvent.WINDOW_EVENT_MASK);
t.setSize(300,300);
t.setVisible(true);

System.out.println("ok.");

} catch (IOException e) {
e.printStackTrace();
}
}
}

在本机运行后返回的console信息:

2919 image/jpeg sun.awt.image.URLImageSource@e2dae9
-1 -1
ok.

...全文
评论 9
收藏 已收藏
分享
返回顶部
wangzhichao_king
Java SE 62,621 成员 307,251 内容