我需要在java中创建许多不同的大型tiff文件,以便将其保存为dataBase中的字节数组。 我只设法复制旧文件,更改它并创建新文件 - 但是要花费太多时间来创建文件(TIFFWriter.createTIFFFromImages)。 我该怎么办?
public byte[] CreateTiff() throws IOException {
try{
File orginialFile = new File("../Dist/dist/attachment/orginialTifFile.TIF");
if(orginialFile!=null){
TIFFReader reader = new TIFFReader(orginialFile);
int length = reader.countPages();
BufferedImage[] images = new BufferedImage[length];
for (int i = 0; i < length; i++) {
images[i] = (BufferedImage)reader.getPage(i);
int rgb = 0x000000; // black
Random rand = new Random();
int x= rand.nextInt(images[i].getHeight()/2);
int y= rand.nextInt(images[i].getWidth()/2);
images[i].setRGB(x, y, rgb);
}
File newAttachmentFile = new File("../Dist/dist/attachment/tempFile.tif");
TIFFWriter.createTIFFFromImages(images, newAttachmentFile);
byte[] b= getBytesFromFile(newAttachmentFile);
return b;
}
}catch(Exception e){
System.out.println("failed to add atachment to request");
e.printStackTrace();
return null;
}
return null;
}
public static byte [] getBytesFromFile(File file)throws IOException { InputStream = new FileInputStream(file); //获取文件的大小 long length = file.length();
if (length > Integer.MAX_VALUE) {
return null;
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
return null;
}
// Close the input stream and return bytes
is.close();
return bytes;
}
由于
答案 0 :(得分:0)
您正在将数据写入文件然后从中读取,这是低效的。尽量避免这种情况。如果你必须给方法一个文件,创建一个假的File类,它返回一个管道,一个arraywriter或类似的东西作为它的outputStream。