2012-05-21 25 views
7

Trong ứng dụng của tôi, tôi có một button1 gọi camera và sau khi chụp ảnh, ảnh phải được lưu vào thư viện thiết bị. Khi tôi bấm vào button2, nó phải mở thư viện, và yêu cầu chọn một hình ảnh. Khi được chọn, nó phải được hiển thị trên imageView bên dưới các nút này.Gọi camera từ một hoạt động, chụp ảnh và tải lên máy chủ

Đây là mã của tôi:

package com.android.imageuploading; 

import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.List; 

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.content.pm.ResolveInfo; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.provider.MediaStore; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ImageView; 

public class ImageUploadingActivity extends Activity { 
    private static final int REQUEST_CODE = 1; 
    private Bitmap bitmap; 
    private ImageView imageView; 
    private Button button_1; 
    public int TAKE_PICTURE = 1; 
    private Button button_2; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     imageView = (ImageView) findViewById(R.id.image); 
     button_1 = (Button) findViewById(R.id.button1); 
     button_1.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 

       Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); 
       startActivityForResult(intent, TAKE_PICTURE); 

      } 
     }); 
     button_2 = (Button) findViewById(R.id.button2); 
     button_2.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 

       pickImage(getCurrentFocus()); 
      } 
     }); 
    } 

    public void pickImage(View view) { 
     Intent intent = new Intent(); 
     intent.setType("image/*"); 
     intent.setAction(Intent.ACTION_GET_CONTENT); 
     intent.addCategory(Intent.CATEGORY_OPENABLE); 
     startActivityForResult(intent, REQUEST_CODE); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) 
      try { 
       // We need to recyle unused bitmaps 
       if (bitmap != null) { 
        bitmap.recycle(); 
       } 
       InputStream stream = getContentResolver().openInputStream(
         data.getData()); 
       bitmap = BitmapFactory.decodeStream(stream); 
       stream.close(); 
       imageView.setImageBitmap(bitmap); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     super.onActivityResult(requestCode, resultCode, data); 
    } 

    public static boolean isIntentAvailable(Context context, String action) { 
     final PackageManager packageManager = context.getPackageManager(); 
     final Intent intent = new Intent(action); 
     List<ResolveInfo> list = packageManager.queryIntentActivities(intent, 
       PackageManager.MATCH_DEFAULT_ONLY); 
     return list.size() > 0; 
    } 
} 

Vấn đề là, khi tôi chụp ảnh, nó yêu cầu lưu hoặc loại bỏ. Khi tôi nhấp vào lưu, ứng dụng của tôi gặp sự cố, nói rằng:

java.lang.RuntimeExceptionEx: Không cung cấp kết quả dữ liệu (có tính năng bổ sung)}} để hoạt động {com.android.imageuploading/com.android.imageuploading.ImageUploadingActivity}: java.lang.NullPointerException

Nơi nào tôi cần phải thay đổi mã?

+0

thể trùng lặp của [Hoạt động Android để mở máy ảnh và tải lên một hình ảnh tới một máy chủ] (http: // stackoverflow .com/questions/10663019/android-hoạt động-to-open-camera-và-upload-an-image-to-a-server) – Sam

Trả lời

4

trong trường hợp của tôi, tôi sử dụng điều này: khi tôi nhấp vào nút lưu hình ảnh lưu và trả lại đường dẫn của tôi trong biến filePath.

String filePath = 
     Environment.getExternalStorageDirectory() +"/your_image_name.jpeg"; 
File file = new File(filePath); 
Uri output = Uri.fromFile(file); 
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, output); 

và trong onactivityresul() tôi sử dụng tệp "tệp này".

+0

không cần chỉ định khi nhấp vào nút lưu ??? ... mã này tự động lưu hình ảnh vào galle ry ?? – Housefly

+0

Tất nhiên bạn gọi phương thức này trên nút bấm button_1.setOnClickListener (mới View.OnClickListener() –

+0

không có tôi đang nói về nút tiết kiệm eh mà có thể nhìn thấy khi chúng ta chụp bất kỳ hình ảnh .... chúng tôi không có tham chiếu đến nút đó ... chúng tôi? – Housefly

4

Capture hình ảnh:

public class Camera extends Activity 
    { 
private static final int CAMERA_REQUEST = 1888; 
private String selectedImagePath; 
WebView webview; 
String fileName = "capturedImage.jpg"; 
private static Uri mCapturedImageURI; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE); 
    startActivityForResult(cameraIntent, CAMERA_REQUEST); 
} 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    if (resultCode == RESULT_OK) { 
     if (requestCode == CAMERA_REQUEST) 
     { 
      Bitmap photo = (Bitmap) data.getExtras().get("data"); 
      ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
      photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 
      Random randomGenerator = new Random();randomGenerator.nextInt(); 
      String newimagename=randomGenerator.toString()+".jpg"; 
      File f = new File(Environment.getExternalStorageDirectory() 
            + File.separator + newimagename); 
      try { 
       f.createNewFile(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      //write the bytes in file 

      try { 
       fo = new FileOutputStream(f.getAbsoluteFile()); 
      } catch (FileNotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      try { 
       fo.write(bytes.toByteArray()); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
       uri=f.getAbsolutePath(); 
    //this is the url that where you are saved the image 
     } 



    } 

Chọn Image:

public class ChoosePicture extends Activity 
    { 
     private static final int SELECT_PICTURE = 1; 
     private String selectedImagePath; 

     @Override 
     public void onCreate(Bundle savedInstanceState) 
     { 
      super.onCreate(savedInstanceState); 
      webview=(WebView)findViewById(R.id.webView1); 
      Intent intent = new Intent(); 
      intent.setType("image/*"); 
      intent.setAction(Intent.ACTION_GET_CONTENT); 
      intent.addCategory(Intent.CATEGORY_OPENABLE); 
      startActivityForResult(intent, SELECT_PICTURE); 
     } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     if (resultCode == RESULT_OK) { 
      if (requestCode == SELECT_PICTURE) 
      { 
       Uri selectedImageUri = data.getData(); 
       selectedImagePath = getPath(selectedImageUri); 
       try { 
        FileInputStream fileis=new FileInputStream(selectedImagePath); 
        BufferedInputStream bufferedstream=new BufferedInputStream(fileis); 
        byte[] bMapArray= new byte[bufferedstream.available()]; 
        bufferedstream.read(bMapArray); 
        Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length); 
    //this is the image that you are choosen 

        if (fileis != null) 
        { 
         fileis.close(); 
        } 
        if (bufferedstream != null) 
        { 
         bufferedstream.close(); 
        } 
       } catch (FileNotFoundException e) {     
        e.printStackTrace(); 
       } catch (IOException e) {     
        e.printStackTrace(); 
       }    
      } 
     } 
    } 


public String getPath(Uri uri) { 
     String[] projection = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = managedQuery(uri, projection, null, null, null); 
     int column_index = cursor 
       .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     return cursor.getString(column_index); 
    } 
} 
Các vấn đề liên quan