2016-07-14 192 views
1

我需要使用分隔符II *將一個tiff文件拆分爲多個tiff文件,因此我使用下面的代碼將tiff文件轉換爲base64並使用子字符串提取第一個圖片 。不過,我得到如下錯誤。請告知如何僅使用此分隔符II *提取tiff文件中的第一張圖像(base64代碼爲SUkq)。將TIFF文件拆分爲多個文件

我可以在不執行子字符串的情況下解碼圖像。

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 
at java.lang.String.substring(String.java:1954) 
at EncodeStringTest.main(EncodeStringTest.java:63) 

類文件

public class EncodeStringTest { 

public static void main(String[] args) { 
    File file = new File("D:\\Users\\Vinoth\\workspace\\image.tif"); 

    try { 
     /* 
     * Reading a Image file from file system 
     */ 
     FileInputStream imageInFile = new FileInputStream(file); 
     byte imageData[] = new byte[(int)file.length()]; 
     imageInFile.read(imageData); 

     /* 
     * Converting Image byte array into Base64 String 
     */ 
     String imageDataString = encodeImage(imageData); 
        System.out.println(imageDataString); 
     String result = imageDataString.substring(imageDataString.indexOf("SUkq") + 1, imageDataString.indexOf("SUkq")); 
     /* 
     * Converting a Base64 String into Image byte array 
     */ 
        System.out.println("Resulted String"+imageDataString); 
     byte[] imageByteArray = decodeImage(result); 

     /* 
     * Write a image byte array into file system 
     */ 
     FileOutputStream imageOutFile = 
          new FileOutputStream("D:\\Users\\Vinoth\\workspace\\image_2.tif"); 
     imageOutFile.write(imageByteArray); 

     imageInFile.close(); 
     imageOutFile.close(); 

     System.out.println("Image Successfully Manipulated!"); 
    } catch (FileNotFoundException e) { 
     System.out.println("Image not found" + e); 
    } catch (IOException ioe) { 
     System.out.println("Exception while reading the Image " + ioe); 
    } 

} 


public static String encodeImage(byte[] imageByteArray){   
    return Base64.encodeBase64URLSafeString(imageByteArray);   
} 


public static byte[] decodeImage(String imageDataString) {  
    return Base64.decodeBase64(imageDataString); 
} 

}

+0

你可以試試這個解決方案,讓我知道你的意見。 https://stackoverflow.com/a/45583553/7731623 –

+0

該代碼不會爲我工作,因爲我的文件包含多個tiff文件在一個單獨的,每個都有一個單獨的元數據。所以這段代碼只會讀取我文件中的第一張圖片。感謝您的建議,我已經找到了解決方案,將圖像轉換爲字節數組,並逐字讀取每個圖像,並將其分配給單獨的輸出流,然後使用twlevemonkeys tiff編寫器將所有流合併到單個tiff。 – Vinoth

回答

0

在此代碼

substring(imageDataString.indexOf("SUkq") + 1, imageDataString.indexOf("SUkq")) 

顯然基於所述錯誤消息的字符串"SUkq"在輸入未找到。因此,本聲明相當於

substring(0,-1) 

哪個無效。您需要添加代碼來處理輸入中不包含您正在查找的文本的情況。

其次,該子字符串將永遠不會工作。既然你開始indexOf一個字符串的兩次開始,即使輸入包含您正在尋找的字符串時,結果總是

substring(n,n-1) 

其中n是目標字符串的位置。這個範圍總是無效的。

目前尚不清楚爲什麼你覺得有必要base64編碼圖像的所有。只需搜索字節數組。 base64字符串將包含SUkq字符串,只有當未編碼的目標字符串從文件起始位置的偏移量的3倍開始時,base64會將3個輸入字節編碼爲4個輸出字節。如果輸入中的分隔符II*發生在其他兩個可能的偏移量之一(模3),則編碼結果將取決於先前和後續數據,因此使用base64將無法正常工作,除非您可以保證偏移量所有情況下的輸入分隔符,並且它始終爲0 mod 3.

哦,下次嘗試單步執行IDE調試器中的代碼。你會很快看到發生了什麼。

+0

謝謝,是否有可能使用bytearray分割TIFF文件? – Vinoth

+0

可以將任何文件「拆分」爲塊。無論這對於TIFF是否有意義(即它是否會產生有效的單獨圖像文件)我都不知道。嘗試一下,找出答案。 –