ImageReader 读取jpeg出错
下面是书上的例子,为什么运行时出错:
Not a JPEG file: starts with 0x00 0x00
jpg文件可以正常打开的呀?
package ch03.image;
import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import
java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class SkiImageClient2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SkiImageClient2 sc2=new SkiImageClient2();
sc2.createImage("telemk");
//sc2.getRawBytes("nordic");
}
public byte[] getRawBytes(String name)
{
System.out.println("Start....");
ByteArrayOutputStream out=new ByteArrayOutputStream();
try
{
String cwd=System.getProperty("user.dir");
String sep=System.getProperty("file.separator");
String base_name=cwd+sep+"jpegs"+sep;
String file_name=base_name+name+".jpg";
FileInputStream in=new FileInputStream(file_name);
if(in==null)
{
System.out.println("in is null");
in=new FileInputStream(base_name+"nordic.jpg");
}
byte[] buffer=new byte[2048];
int n=0;
while ((n=in.read())!=-1)
out.write(buffer,0,n);
in.close();
System.out.println("End....");
}
catch(
IOException e)
{
System.out.println(e.getMessage());
}
return out.toByteArray();
}
public Image createImage(String name)
{
byte[] bytes=getRawBytes(name);
ByteArrayInputStream in=new ByteArrayInputStream(bytes);
Iterator iterators=ImageIO.getImageReadersByFormatName("jpg");
ImageReader iterator=(ImageReader)iterators.next();
try
{
ImageInputStream iis=ImageIO.createImageInputStream(in);
iterator.setInput(iis,true);
return iterator.read(0);
}
catch(IOException e)
{
System.out.println("Error");
System.err.print(e.getMessage());
return null;
}
//return null;
}
}
------解决方案--------------------