2016-01-12 213 views
2

嘗試壓縮位圖時出現空指針異常,所以我可以將它發送到ByteArrayOutputStream以獲取字節數組。我需要這個字節數組,因此我可以將圖像作爲ParseFile上傳到我的Parse數據庫。日誌錯誤如下所示。嘗試壓縮位圖時發生空指針異常

01-11 23:29:41.522 32015-32015/com.example.whhsfbla.fashionnow E/AndroidRuntime: FATAL EXCEPTION: main 
Process: com.example.whhsfbla.fashionnow, PID: 32015 
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference 
    at com.example.whhsfbla.fashionnow.PostActivity.uploadPost(PostActivity.java:140) 
    at com.example.whhsfbla.fashionnow.PostActivity.access$100(PostActivity.java:34) 
    at com.example.whhsfbla.fashionnow.PostActivity$2.onClick(PostActivity.java:92) 
    at android.view.View.performClick(View.java:5254) 
    at android.view.View$PerformClick.run(View.java:21179) 
    at android.os.Handler.handleCallback(Handler.java:739) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:145) 
    at android.app.ActivityThread.main(ActivityThread.java:6837) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

這會導致錯誤的代碼行是bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

public class PostActivity extends Activity { 

    private final int SELECT_PHOTO = 1; 
    private InputStream imageStream; 
    private Uri uploadFileUri; 
    private Bitmap bitmap; 
    private TextView txtPostTitle; 
    private EditText editText; 
    private Button btnChoosePic, btnUploadPost; 
    private ImageView imgPreview; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_post); 

     txtPostTitle = (TextView) findViewById(R.id.txtPostTitle); 
     editText = (EditText) findViewById(R.id.editText); 
     btnChoosePic = (Button) findViewById(R.id.btnChoosePic); 
     btnUploadPost = (Button) findViewById(R.id.btnMakePost); 
     imgPreview = (ImageView) findViewById(R.id.imgPreview); 

     txtPostTitle.setText("Title:"); 
     btnChoosePic.setText("Choose Picture"); 
     btnUploadPost.setText("Create Post"); 
     btnUploadPost.setEnabled(false); 

     /*btnChoosePic.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       try { 
        openImageIntent(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); */ 

     btnChoosePic.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       try { 
        openImageIntent(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 

     btnUploadPost.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       uploadPost(); 
       finish(); 
      } 
     }); 

    } 

    private void openImageIntent() throws IOException { 
     final File root = new File(Environment.getExternalStorageDirectory() + 
       File.separator + "MyDir" + File.separator); 
     root.mkdirs(); 
     final String fileName = File.createTempFile("tmp", ".txt").getPath(); 
     final File sdImageMainDirectory = new File(root, fileName); 

     uploadFileUri = Uri.fromFile(sdImageMainDirectory); 

     //Camera 
     final List<Intent> cameraIntents = new ArrayList<Intent>(); 
     final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     final PackageManager packageManager = getPackageManager(); 
     final List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(captureIntent, 0); 
     for (ResolveInfo res : resolveInfoList) { 
      final String packageName = res.activityInfo.packageName; 
      final Intent intent = new Intent(captureIntent); 
      intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); 
      intent.setPackage(packageName); 
      intent.putExtra(MediaStore.EXTRA_OUTPUT, uploadFileUri); 
      cameraIntents.add(intent); 
     } 

     //Filesystem 
     final Intent galleryIntent = new Intent(); 
     galleryIntent.setType("image/*"); 
     galleryIntent.setAction(Intent.ACTION_GET_CONTENT); 

     final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source"); 

     chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()])); 

     startActivityForResult(chooserIntent, SELECT_PHOTO); 
    } 

    private void uploadPost() { 
     // Locate the image in res > drawable-hdpi 
     bitmap = BitmapFactory.decodeResource(getResources(), R.id.imgPreview); 
     // Convert it to byte 
     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     // Compress image to lower quality scale 1 - 100 
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
     byte[] image = stream.toByteArray(); 

     // Create the ParseFile 
     ParseFile file = new ParseFile("image.png",image); 
     // Upload the image into ParseCloud 
     file.saveInBackground(); 

     // Create a New Class called "ImageUpload" in Parse 
     ParseObject post = new ParseObject("Post"); 

     // Create a column named "ImageName" and set the string 
     post.put("title", editText.getText().toString()); 

     // Create a column named "ImageFile" and insert the image 
     post.put("ImageFile", file); 

     post.put("user", User.username); 

     // Create the class and the columns 
     post.saveInBackground(); 

     // Show a simple toast message 
     Toast.makeText(PostActivity.this, "Post Uploaded", 
       Toast.LENGTH_SHORT).show(); 


    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent imageIntent) { 
     super.onActivityResult(requestCode, resultCode, imageIntent); 

     if (resultCode == RESULT_OK) { 
      if (requestCode == SELECT_PHOTO) { 
       //Get the URI 
       final boolean isCamera; 
       if (imageIntent == null) { 
        isCamera = true; 
       } else { 
        final String action = imageIntent.getAction(); 
        if (action == null) { 
         isCamera = false; 
        } else { 
         isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE); 

        } 
       } 

       Uri selectedImageUri; 
       if (isCamera) { 
        selectedImageUri = uploadFileUri; 
       } else { 
        selectedImageUri = imageIntent == null ? null : imageIntent.getData(); 
       } 

       //Get the Bitmap from the URI, and set it to the ImageView 
       try { 
        imageStream = getContentResolver().openInputStream(selectedImageUri); 
        final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream); 
        imgPreview.setImageBitmap(selectedImage); 
        btnUploadPost.setEnabled(true); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 
+1

事實並非如此,根據文檔:http://developer.android.com/reference /android/graphics/BitmapFactory.html#decodeResource%28android.content.res.Resources,%20int,%20android.graphics.BitmapFactory.Options%29。如果「圖像數據無法解碼」,它可以返回null。 – Szymon

+0

@MikeM。如何從ImageView中獲取R.drawable?我無法通過ImageView.getDrawable()作爲參數,因爲它應該是一個int。 –

+1

@MikeM。你是對的。對不起這是我的錯。 – Szymon

回答

8

你得到一個空指針異常,因爲bitmap爲空。替換去

bitmap = BitmapFactory.decodeResource(getResources(), R.id.imgPreview); 

與此

bitmap = ((BitmapDrawable) imgPreview.getDrawable()).getBitmap(); 
+0

保存了我的一天...我改變了我的代碼這一行'Bitmap bitmap = imageView.getDrawingCache();'to'Bitmap bitmap =((BitmapDrawable)imageView.getDrawable())。getBitmap();' – crakama

1

,如果你使用的是PNG格式的話,由於PNG是一種無損格式,它不會壓縮圖像。使用JPEG壓縮yourimage並使用0而不是100質量。

然後用

Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(stream.toByteArray())); 
+2

這與這個問題有什麼關係?當然PNG壓縮。有損或無損與此無關。 –

0

行嘗試使用Bitmap.createScaledBitmap

Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter);

相關問題