6

ユーザーはnamenoteimageの3 つのデータを保存 します。以下のコードを見るとわかるように、名前とメモをサーバー側に送信するコードに成功しました。しかし、選択した画像ファイルをデバイスからserverDBに送信する方法がわかりません。

public class AddEditWishlists extends Activity {

    // Client-Server - Start //////////////////////
    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputDesc;

    // 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";
    // 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");

            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();


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

                            // 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);

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

                            // Client-Server - End ////////////////////////////////////

                            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);
            }

        }
    }

}

画像ファイルを送信するためにクライアント サーバー アノテーション間でコーディングするにはどうすればよいですか?..

4

4 に答える 4

6

選択した画像を Base 64 文字列に変換し、その文字列をサーバーに渡し、サーバーでデコードすることができます。

画像を base64 に変換するには、このコードを確認してください。imageView がある場合は、このコードを記述できます。

imageView.buildDrawingCache();
Bitmap bm = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();

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

編集

コードのように、この行にバイト配列があります。

image = extras.getByteArray("blob");

その後、このコード行を直接記述できます。

String encodedImage = Base64.encodeToString(image , Base64.DEFAULT);
于 2013-05-08T17:47:24.527 に答える
0
 # handling in Asp.Net MVC #

 public string Post( string PostText, byte[] image)
      {
        PostCS PostCs = new PostCS();
        ImageResize obj = new ImageResize();
        string FileName = DateTime.Now.ToFileTime().ToString().Trim();
        string imgName;        

        if (image != null)
        {
            ImageFormat png = ImageFormat.Png;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(image))
            {
                System.Drawing.Image bp = System.Drawing.Image.FromStream(ms, true);
                //Bitmap bp = new Bitmap(Image.FromStream(ms));
                imgName = FileName + "_" + bp.Width + "X" + bp.Height + ".png";
                bp.Save(Server.MapPath(ConfigurationManager.AppSettings["WallPostImages"].ToString()) + imgName, png);
                PostCs.ImageName = imgName;                   
                PostCs.InsertPostImg(PostCs);


            }
            var resizemaster = from a in LQdb.Z_ImageSetups select a;
            int wallwidth = 640;
            int wallheight = 480;             

            string orginalfilename = Server.MapPath(ConfigurationManager.AppSettings["WallPostImages"].ToString()) + imgName;
            obj.ImageStream(FileName, ConfigurationManager.AppSettings["WallPostImages"].ToString(), wallwidth, wallheight, orginalfilename, out imgName);
            PostCs.ImageName = imgName;
            PostCs.ImageType = "Wall";
            PostCs.InsertPostImg(PostCs);


        }
        return PostText;
    }
于 2014-10-16T10:18:05.763 に答える
0
public class AddPost extends ActionBarActivity {
protected ImageButton imgButton;// To refer image button
protected ImageView image;

// To refer image view
protected ImageButton ImageFromCard;
private static int RESULT_LOAD_IMAGE = 2;

private ProgressDialog PDialog;
Button btnLogout;
@SuppressWarnings("unused")
private boolean imgCapFlag = false;
protected boolean taken;
protected static final String PHOTO_TAKEN = "photo_taken";
protected String path;
private Bitmap bitmap;

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

    image = (ImageView) findViewById(R.id.image);

    imgButton = (ImageButton) findViewById(R.id.imageButton1);
    imgButton.setOnClickListener(new ButtonClickHandler());
    ImageFromCard = (ImageButton) findViewById(R.id.imageButton2);

    path = Environment.getExternalStorageDirectory()
            + "/images/make_machine_example.jpg";

    // ---------------------MEMORY CARD OPEN----------------------------

    ImageFromCard.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });

    // ------------------URL FOR CATEGORIES--------------------

}

public void seepost(View view) {
    Intent i = new Intent(view.getContext(), MainActivity.class);
    startActivity(i);
}

// ---------Handling Image Result---------------------

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
            && null != data) {
        Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
        cursor.close();

        BitmapFactory.Options options = new BitmapFactory.Options();
        bitmap = BitmapFactory.decodeFile(picturePath);
        // Set ImageView with the bitmap read in the prev line
        image.setImageBitmap(bitmap);

    } else {

        // Log message
        Log.i("SonaSys", "resultCode: " + resultCode);
        switch (resultCode) {
        // When user doesn't capture image, resultcode returns 0
        case 0:
            Log.i("SonaSys", "User cancelled");
            break;
        // When user captures image, onPhotoTaken an user-defined method to
        // assign the capture image to ImageView
        case -1:
            onPhotoTaken();
            break;

        }

    }

}

// ----------------------------------------------------

public class ButtonClickHandler implements View.OnClickListener {
    public void onClick(View view) {
        // Below log message will be logged when you click Take photo button
        Log.i("SonaSys", "ButtonClickHandler.onClick()");
        // Call startCameraActivity, an user defined method, going to be
        // created
        startCameraActivity();
    }
}

protected void startCameraActivity() {
    // Log message
    Log.i("SonaSys", "startCameraActivity()");
    // Create new file with name mentioned in the path variable
    File file = new File(path);

    Uri outputFileUri = Uri.fromFile(file);
    Intent intent = new Intent(
            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

    startActivityForResult(intent, 0);
}

protected void onPhotoTaken() {
    // Log message
    Log.i("SonaSys", "onPhotoTaken");
    // Flag used by Activity life cycle methods
    taken = true;
    // Flag used to check whether image captured or not
    imgCapFlag = true;
    // BitmapFactory- Create an object
    BitmapFactory.Options options = new BitmapFactory.Options();
    // Set image size
    options.inSampleSize = 4;
    // Read bitmap from the path where captured image is stored
    bitmap = BitmapFactory.decodeFile(path, options);
    // Set ImageView with the bitmap read in the prev line
    image.setImageBitmap(bitmap);

}

// ----------------Image Upload ------------------------------

public void postData(View view) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://sitename.net/controllername/post");

    try {

        if (bitmap != null) {

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            String file = Base64.encodeBytes(data);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    7);

            nameValuePairs.add(new BasicNameValuePair("image", file));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            httpclient.execute(httppost);

        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}
于 2014-10-16T10:06:48.290 に答える