2011-04-11 89 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方法的兴趣。