开发者

How to create TIFF file?

I开发者_开发问答 need to create many different large tiff files in java for save it as byte array in dataBase. I only managed to copy old file, change it and create new one - but it take too much time to crete the file(TIFFWriter.createTIFFFromImages). what can I do?

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 is = new FileInputStream(file); // Get the size of the 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;
}

Thanks


You're writing data to a file and then reading from it, that's inefficient. Try to avoid that. If you have to give the method a File, create a fake File class that returns a pipe, an arraywriter or something like that as its outputStream.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜