在Asynctask中从raw获取图像

时间:2014-02-23 08:25:14

标签: android

我使用asynctask进行图像处理。我需要比较两个图像。我有原始图像来自res / raw文件夹和CompareImage来自相机拍摄的图像。问题是我试图从我的res / raw获取原始图像。它刚刚停止。

  • 错误是我试图从res / raw获取原始图像。 OriginalImage = GetRawImage(x,res);

请帮忙。谢谢。

这是我的代码。

public class CameraActivity extends Activity {

    // Member fields.
    private ProgressDialog pd;
    private ImageView mImage;
    Bitmap CompareImage = null;
    Bitmap OriginalImage = null;
    double Cr2,Cg2,Cb2;

    // Constants.
    public final int CAMERA_NO_FILEPATH = 0;
    public final int CAMERA_WITH_FILEPATH = 1;
    String timeStamp;
    String ImageName=null;
    Resources res;

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

        res = getResources();
        mImage = (ImageView) findViewById(R.id.camera_image);
        timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        ImageName = "Img_"+ timeStamp + ".jpg";

        File file = new File(getOutputLink(ImageName));
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(cameraIntent, CAMERA_WITH_FILEPATH);

    }

    /*
     * Creates a new file path into the standard Android pictures directory.
     */
    private String getOutputLink(String filename) {
        String directory = "";

        // Check if storage is mounted.
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), 
                                                    getResources().getString(R.string.app_name));
            // Create the storage directory if it does not exist.
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    return null;
                }
            }
            directory = mediaStorageDir.getPath() + File.separator +  filename;
        }
        return directory;
    }

    /*
     * Creates a new file path into the standard Android pictures directory.
     */
    private String getLibLink(String filename) {
        String directory = "";

        // Check if storage is mounted.
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), 
                                                    "ImageLib");
            // Create the storage directory if it does not exist.
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    return null;
                }
            }
            directory = mediaStorageDir.getPath() + File.separator + filename;
        }
        return directory;
    }


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

        if (resultCode == RESULT_OK) {
            if (requestCode == CAMERA_NO_FILEPATH) {
            } else if (requestCode == CAMERA_WITH_FILEPATH) {

                final String filepath = getOutputLink(ImageName);
                final Bitmap img = BitmapFactory.decodeFile(filepath);
                mImage.setImageBitmap(img);

                final ArrayList<String> list = new ArrayList<String>();

                Button NextButton = (Button) findViewById(id.NextButton);
                NextButton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        //Progress Dialog and Async Task while processing the image.
                        AsyncTask<String, String, String> task = new AsyncTask<String, String, String>(){

                            @Override
                            protected void onPreExecute(){
                                super.onPreExecute();
                                pd = new ProgressDialog(CameraActivity.this);
                                pd.setMessage("Processing. Please wait...");
                                pd.setIndeterminate(true);
                                pd.setCancelable(true);
                                pd.show();
                            }

                            @Override
                            protected String doInBackground(String... arg0) {
                                try {
                                    CompareImage = img;

                                    for(int x=1;x<2;x++){
                                        // This code isnt working.
                                        OriginalImage = GetRawImage(x,res);
                                        // This code isnt working.

                                        int width1 = OriginalImage.getWidth();
                                        int width2 = CompareImage.getWidth();
                                        int height1 = OriginalImage.getHeight();
                                        int height2 = CompareImage.getHeight();
                                        double result=0;

                                        // Resize the bitmap if it is not match.
                                        if ((width1 != width2) || (height1 != height2)) {
                                            Bitmap Newsize = Bitmap.createScaledBitmap(CompareImage, width1, height1, false);
                                            CompareImage = Newsize;
                                        }

                                        width2 = CompareImage.getWidth();
                                        height2 = CompareImage.getHeight();

                                        long diff = 0;

                                        for (int i = 0; i < width1; i++) {
                                            for (int j = 0; j < height1; j++) {
                                              int rgb1 = OriginalImage.getPixel(i, j);
                                              int rgb2 = CompareImage.getPixel(i, j);
                                              int r1 = (rgb1 >> 16) & 0xff;
                                              int g1 = (rgb1 >>  8) & 0xff;
                                              int b1 = (rgb1      ) & 0xff;
                                              int r2 = (rgb2 >> 16) & 0xff;
                                              int g2 = (rgb2 >>  8) & 0xff;
                                              int b2 = (rgb2      ) & 0xff;
                                              diff += Math.abs(r1 - r2);
                                              diff += Math.abs(g1 - g2);
                                              diff += Math.abs(b1 - b2);
                                            }
                                          }

                                          double n = width1 * height1 * 3;
                                          double p = diff / n / 255.0;
                                          result = (100-(p * 100.0));
                                          list.add(Topics(x) + "-" + String.format("%.2f",result) + "%");
                                    }

                                } catch (Exception e) {
                                    // TODO Auto-generated catch block
                                    list.add("Error ");
                                }
                                return null;
                            }

                            @Override
                            protected void onPostExecute(String arg0){
                                super.onPostExecute(arg0);
                                pd.dismiss();
                                Intent intent = new Intent(CameraActivity.this,ResultActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.putStringArrayListExtra("list", list);
                                getApplicationContext().startActivity(intent);
                            }
                        };
                        task.execute("");
                    }
                });

            }
        }
    }

    private final Bitmap GetLibImage(String filename){
        String filepath = getLibLink(filename);
        return BitmapFactory.decodeFile(filepath);
    }

    private static Bitmap GetRawImage(int i,Resources res){
        Bitmap myBitmap = null;
        switch (i) {

        case 1:
            myBitmap = BitmapFactory.decodeResource(res, R.raw.img_skeletalsystem);
            break;

        case 2:
            myBitmap = BitmapFactory.decodeResource(res, R.raw.img_structureofbone);
            break;

        case 3:
            myBitmap = BitmapFactory.decodeResource(res, R.raw.img_injuriesanddiseases);
            break;

        case 4:
            myBitmap = BitmapFactory.decodeResource(res, R.raw.img_propercareofbones);
            break;

        case 5:
            myBitmap = BitmapFactory.decodeResource(res, R.raw.img_kindsofmuscles);
            break;

        default:
            break;
        }
         return myBitmap;
    }

    private String Topics(int i){
        String topic = null;
        switch (i) {
        case 1:
            topic="Skeletal System";
            break;
        case 2:
            topic="Structure of Bones";
            break;
        case 3:
            topic="Injuries and Diseases of Bones";
            break;
        case 4:
            topic="Proper care of Bones";
            break;
        case 5:
            topic="Kinds of Muscles";
            break;
        default:
            break;
        }
        return topic;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_camera, menu);
        return true;
    }

}

0 个答案:

没有答案