2014-01-15 52 views
0

我想從輸入流獲取位圖,然後調整其大小。但我得到空指針異常。解碼後如何從輸入流獲取位圖

我嘗試inputstream.reset()但不工作。

任何人都可以幫忙嗎?

BufferedInputStream my_is = new BufferedInputStream(is); 
       Bitmap bit   = null; 

       final BitmapFactory.Options options = new BitmapFactory.Options(); 
       options.inJustDecodeBounds = true; 
       BitmapFactory.decodeStream(my_is, null, options); 

       // Calculate inSampleSize 
       options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

       // Decode bitmap with inSampleSize set 
       options.inJustDecodeBounds = false; 

       try { 
        my_is.reset(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

       bit  = BitmapFactory.decodeStream(my_is, null, options); 

       String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", 
         Locale.getDefault()).format(new Date()); 
       FileOutputStream fos = null; 
       try { 
        fos = getActivity().openFileOutput(timeStamp + ".png", Context.MODE_PRIVATE); 
        bit.compress(Bitmap.CompressFormat.PNG,90,fos); 
        fos.close(); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

       crud.update_photo_path(String.valueOf(position), timeStamp); 

       return bit; 
+1

爲什麼重讀從流時,你已經擁有了'Bitmap',你可以直接調整呢? 'Bitmap scaled = Bitmap.createScaledBitmap(largeBitmap,h,w,true);' – CaseyB

+0

@CaseyB thanx你很棒:D很容易修復我的問題 –

回答

0

我用這個utils的:

public static Bitmap decodeSampledBitmapFromResource(String uri, 
     int reqWidth, int reqHeight) { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(uri, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, 
      reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeFile(uri, options); 
} 

private static int calculateInSampleSize(BitmapFactory.Options options, 
     int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 
     if (width > height) { 
      inSampleSize = Math.round((float) height/(float) reqHeight); 
     } else { 
      inSampleSize = Math.round((float) width/(float) reqWidth); 
     } 
    } 
    return inSampleSize; 
} 
+0

BitmapFactory.decode文件函數正在工作,但BitmapFactory.decodeStream()函數不工作 –