2011-04-11 37 views
0

我試圖將.jpg文件解碼爲位圖並從位圖文件中讀取原始數據。 以下是我的應用程序的代碼片段。從位圖文件中讀取原始數據

File file = new File(Environment.getExternalStorageDirectory(),"test.jpg"); 

    int top = 450; 
    int left = 0; 

    int right= 1450; 
    int bottom = 2592; 

    int width = right-top; 
    int height = bottom-left; 

    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inPreferredConfig = Bitmap.Config.ARGB_8888; 

    bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options); 

    Bitmap bitmapScaled = Bitmap.createBitmap(bitmap, top, left, width, height); 
    bitmap.recycle(); 

    ByteBuffer buffer = ByteBuffer.allocate(width*height*4); 
    bitmapScaled.copyPixelsToBuffer(buffer); 

    bitmapScaled.recycle(); 

    File file2 = new File(Environment.getExternalStorageDirectory(),"decodeFile"); 

    FileOutputStream out = new FileOutputStream(file2.getAbsolutePath()); 
    out.write(buffer.array()); 

在上面的代碼中,即時通訊試圖讀取來自位圖文件中的原始數據轉換成的ByteBuffers並存儲到在SDCARD新創建的文件(decodeFile)。

當我看到「decodeFile」中的數據時,一半的數據將變爲null,並且數據不正確。

以上是使用Bitmap類方法讀取原始數據的一種方法。

當我通過使用下面的代碼片段遵循相同的事情,即時獲取正確的數據。

BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(file1.getAbsolutePath(), true); 
Bitmap bitmap1 = bitmapRegionDecoder.decodeRegion(new Rect(top,left,width,height),options); 
ByteBuffer buffer = ByteBuffer.allocate(width*height*4); 
    bitmapScaled.copyPixelsToBuffer(buffer); 

    bitmapScaled.recycle(); 

File file2 = new File(Environment.getExternalStorageDirectory(),"regionFile"); 

    FileOutputStream out = new FileOutputStream(file2.getAbsolutePath()); 
    out.write(buffer.array()); 

如果我使用此代碼段,我會得到正確的數據。但是使用BitmapRegionDecoder的缺點是內存泄漏。該應用程序每次將失去1.5 MB的內存,它會執行此API。此內存也不可能用GC回到應用程序。

所以任何機構可以幫我如何將數據從位圖複製到另一個文件,而不會丟失數據..這將是對我非常有幫助,如果任何機構對此作出迴應..提前

謝謝

+0

請格式化代碼下次:) – MByD 2011-04-11 11:33:42

+0

@MByD謝謝你的建議 – uday 2011-04-11 13:27:45

+0

格式化....... – 2011-08-25 15:53:55

回答

0

見我的回答我自己的問題here

你會在onActivityResult方法的興趣。