0

我正在对从图库中选择的图像进行编码,并希望将其发送到服务器。我成功发送了文本形式的产品名称和描述。但是,我不知道如何编码图像并将其发送为字符串形式。在服务器端,我需要用 php 对其进行解码。我的代码是...

public class AddEditWishlists extends Activity {

// Client-Server - Start //////////////////////

JSONParser jsonParser = new JSONParser();

// url to create new product
private static String url_create_product = "http://10.56.43.91/android_connect/create_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
InputStream is;
// Client-Server - End //////////////////////


//Define Variables
private EditText inputname;
private EditText inputnote;
private Button upload;
private Bitmap yourSelectedImage;
private ImageView inputphoto;
private Button save;
private int id;
private byte[] blob=null;
byte[] image=null;

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

private void setUpViews() {

    inputname = (EditText) findViewById(R.id.inputname);
    inputnote = (EditText) findViewById(R.id.inputnote);
    inputphoto = (ImageView) findViewById(R.id.inputphoto); 

    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        id=extras.getInt("id");
        inputname.setText(extras.getString("name"));
        inputnote.setText(extras.getString("note"));

        image = extras.getByteArray("blob");

        String encodedImage = Base64.encodeToString(image , Base64.DEFAULT);

        if (image != null) {
            if (image.length > 3) {
                inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
            }
        }       
    }



    //Image Upload Button
    upload = (Button) findViewById(R.id.upload);
    upload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, 0);
        }
    });




    // Save the data
    save = (Button) findViewById(R.id.save);

    // Save하면 발생되는 이벤트
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {


            if (inputname.getText().length() != 0) {
                AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
                    @Override
                    protected Object doInBackground(Object... params) {
                        saveContact();



                        // Client-Server - Start //////////////////////////////////////
                        String name = inputname.getText().toString();
                        String description = inputnote.getText().toString();
                        //String photo = inputphoto.getContext().toString();
                        encodedImage = yourSelectedImage.toString();

                        // Building Parameters
                        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                        params1.add(new BasicNameValuePair("name", name));
                        params1.add(new BasicNameValuePair("description", description));
                        params1.add(new BasicNameValuePair("photo", encodedImage));

                        Log.v("log_tag", System.currentTimeMillis()+".jpg");



                        // getting JSON Object
                        // Note that create product url accepts POST method
                        JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1);

                        // check log cat fro response
                        Log.d("Create Response", json.toString());

                        // check for success tag
                        try {
                            int success = json.getInt(TAG_SUCCESS);


                            Log.v("log_tag", "In the try Loop" );

                            if (success == 1) {
                                // closing this screen
                                finish();
                            } else {
                                // failed to create product
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }



                        return null;
                    }

                    @Override
                    protected void onPostExecute(Object result) {
                        finish();
                    }
                };

                saveContactTask.execute((Object[]) null);

            } else {
                AlertDialog.Builder alert = new AlertDialog.Builder(
                        AddEditWishlists.this);
                alert.setTitle("Error In Save Wish List");
                alert.setMessage("You need to Enter Name of the Product");
                alert.setPositiveButton("OK", null);
                alert.show();
            }
        }
    });
}


// If users save data, this will act (data -> db) 
private void saveContact() {

    if(yourSelectedImage!=null){
        ByteArrayOutputStream outStr = new ByteArrayOutputStream();
        yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
        blob = outStr.toByteArray();
    }



    else{blob=image;}

    // Change Text type to string type to save in the DB
    SQLiteConnector sqlCon = new SQLiteConnector(this);

    if (getIntent().getExtras() == null) {
        sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
    }

    else {
        sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(), blob);
    }


}

@Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
    super.onActivityResult(requestCode, resultCode, resultdata);
    switch (requestCode) {
    case 0:
        if (resultCode == RESULT_OK) {
            Uri selectedImage = resultdata.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);

            cursor.close();
            // Convert file path into bitmap image using below line.
            yourSelectedImage = BitmapFactory.decodeFile(filePath);
            inputphoto.setImageBitmap(yourSelectedImage);
        }

    }
}

我正在做的是这里的部​​分

if (extras != null) {
        id=extras.getInt("id");
        inputname.setText(extras.getString("name"));
        inputnote.setText(extras.getString("note"));

        image = extras.getByteArray("blob");

        //Here..I encoded the image ***********Is it correct?**********
        String encodedImage = Base64.encodeToString(image , Base64.DEFAULT);

        if (image != null) {
            if (image.length > 3) {
                inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
            }
        }       
    }

和...

                        // Client-Server - Start //////////////////////////////////////
                        String name = inputname.getText().toString();
                        String description = inputnote.getText().toString();

// this line should be modified i guess....                                           
String encodedImage = yourSelectedImage.toString();

                        // Building Parameters
                        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                        params1.add(new BasicNameValuePair("name", name));
                        params1.add(new BasicNameValuePair("description", description));


// This line should be modified i guess..
params1.add(new BasicNameValuePair("photo", encodedImage));

                        Log.v("log_tag", System.currentTimeMillis()+".jpg");



                        // getting JSON Object
                        // Note that create product url accepts POST method
                        JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1);

                        // check log cat fro response
                        Log.d("Create Response", json.toString());

我在应该更正的地方写了注释..我认为那部分出错了..

还有一个问题是,在服务器端,接收编码的照片应该是什么格式?瓦查尔?字符?...

先感谢您。

4

0 回答 0