任何人都可以帮助我捕获图像,在imageView中显示,存储在图库中,将该图像上传到服务器?

时间:2014-05-17 03:59:09

标签: php android image

我想做一个相机捕获,图库存储在图库中,在屏幕上的图像视图中显示,并使用php,json将图像上传到服务器。我有它工作的JSON解析器代码。图像保存为" temp"并被覆盖(我不想要,因为我想要图库中的所有图片)我在下面发布我的代码,请指导我。

public class CamActivity extends Activity 
{      
    private ImageView img;
    int boundBoxInDp;
    private static final int CAMERA_REQUEST = 1888; 
    Button bt1,bt2,btn;
    ContentValues values;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;           

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {  
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cam);


        String path = android.os.Environment.getExternalStorageDirectory()+ File.separator
                + "sdcard" + File.separator + "sdcard";
        img = (ImageView)findViewById(R.id.imageView1);// Assign imageview
        BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();//get image drawable and assign to bitmap drawable
        final Bitmap bmap = drawable.getBitmap();//assign bitmap drawable to bmap which is a bitmap image variable

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        bmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);// this and the line above can be ignored

        //START CAMERA ON LAUNCH OF PAGE
        Intent camera_intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

        // Save code here
        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.png");
        camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        //Save code ends    

        startActivityForResult(camera_intent, CAMERA_REQUEST);
        //START CAMERA ON LAUNCH OF PAGE ENDS

        bt1=(Button)findViewById(R.id.button1);//button to go to next page
        bt1.setOnClickListener (new OnClickListener()//click button to travel to the next page
        {
            public void onClick(View v) 
            {
                img = (ImageView)findViewById(R.id.imageView1);
                img.setScaleType(ScaleType.MATRIX);
                BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
                drawable.setFilterBitmap(true);
                final Bitmap bmap = drawable.getBitmap();

                //convert starts WORKS 
                //convert Bitmap to grayscale 
                Bitmap imgToGreyScale;
                imgToGreyScale = toGrayscale(bmap);  

                //convert to threshold
                Bitmap imgToBlackWhite;
                imgToBlackWhite = ConvertToThreshold(imgToGreyScale); 

                //set ImageView
                ImageView imgbit;
                imgbit = (ImageView) findViewById(R.id.imageView1);
                imgbit.getImageMatrix();
                imgbit.setImageBitmap(imgToBlackWhite);

                //conversion ends WORKS
                Intent intent2 = new Intent(CamActivity.this,QrCodeActivity.class);
                startActivity(intent2);
            }
        });
    }

    // FUNCTION STARTS--------------------------------------------------------------------------------------------
    //Threshold Function -WORKS-
    public Bitmap ConvertToThreshold(Bitmap anythingBmap)
    {
        int width = anythingBmap.getWidth();
        int height = anythingBmap.getHeight();
        int threshold = 120;
        for(int x=0;x<width;x++){
            for(int y=0;y<height;y++){

                int pixel = anythingBmap.getPixel(x, y);
                int gray = Color.red(pixel);
                if(gray < threshold){
                    anythingBmap.setPixel(x, y, 0xFF000000);
                } else{
                    anythingBmap.setPixel(x, y, 0xFFFFFFFF);
                }
            }
        }
        return anythingBmap;
    }
    //Threshold function ends

    // Grayscale Function -WORKS-
    public Bitmap toGrayscale(Bitmap bmpOriginal){        
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();    

        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGrayscale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);
        return bmpGrayscale;
    }

    // Grayscale Function ends


    //FUNCTIONS ENDS----------------------------------------------------------------------------------------    

    //ONResult activity to get image
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {                   
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) 
        { 
            {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) //Click and store
                {
                    if (temp.getName().equals("temp.png")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions); 
                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();//
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    img.setImageBitmap(bitmap);

                    Bitmap GreyScaleBitmap =toGrayscale(bitmap);//UPLOAD THIS
                    upload(GreyScaleBitmap);
                    Bitmap ThresholdBitmap= ConvertToThreshold(bitmap);//UPLOAD THIS


                    String path = android.os.Environment.getExternalStorageDirectory()+ File.separator
                            + "sdcard" + File.separator + "sdcard";
                    //f.delete();
                    OutputStream outFile = null;

                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".png" +"");
                    try 
                    {
                        outFile = new FileOutputStream(file);
                        outFile.flush();
                        outFile.close();
                    } catch (FileNotFoundException e) 
                    {
                        e.printStackTrace();
                    } catch (IOException e) 
                    {
                        e.printStackTrace();
                    } catch (Exception e) 
                    {
                        e.printStackTrace();
                    }
                } catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }
        } 
    }

    private void upload(Bitmap greyScaleBitmap) {

        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        greyScaleBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://example.com/imagestore/post");
        MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
        byte [] ba = bao.toByteArray();
        try {
            entity.addPart("img", new StringBody(new String(bao.toByteArray())));
            httppost.setEntity(entity);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // Execute HTTP Post Request
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
}       
    }
}

Php代码在

之下
<?php

require("config.inc.php");

$target_path = "/uploads/";
$base=$_REQUEST['image'];
$name=$_REQUEST['cmd'];
echo $base;
echo $name;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
// print($binary);
//$theFile = base64_decode($image_data);
$file = fopen($target_path, 'wb');
$file = fopen($name, 'wb');
fwrite($file, $binary);
fclose($file);
//move_uploaded_file($file,$target_path.$name);
copy($name,$target_path.$name); 
?>

1 个答案:

答案 0 :(得分:0)

PHP代码中您错误地覆盖$file对象

的问题
$file = fopen($target_path, 'wb');
$file = fopen($name, 'wb');

应替换为以下内容:

$file = fopen($target_path.$name, 'wb');

您还可以使用rand()或时间戳(即time())将随机数附加到文件名