1

我必须制作一个 android 应用程序,用户可以在其中浏览图库或相机中的图像。然后将图像转换为字符串,然后上传到本地服务器。在服务器上,图像被再次转换并存储为图像。我压缩了图片但是无法上传请帮帮我

下面是代码..

    package com.example.hdfcuploadapp;



import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import android.util.Base64;
import android.app.Activity;``
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;


public class MainActivity extends Activity {

    private static final int REQ_CODE_PICK_IMAGE = 1;
    private static final int CAMERA_REQUEST = 1888;
    private static View popupView = null;
    private static PopupWindow popupWindow = null;
    private static Button buttonBrowse = null;
    private static String compressedImage = null;
    private static Point position = null;
    private static Bitmap imageSelected = null;
    private static String selectedImageRealPath = null;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         Button buttonUpload = (Button) findViewById(R.id.buttonUpload);

         buttonUpload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {



            }
        });

      buttonBrowse = (Button) findViewById(R.id.buttonBrowse);

        buttonBrowse.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(position!= null){
                    showPopup(MainActivity.this, position);
                }           
            }

            @SuppressWarnings("deprecation")
            private void showPopup(final Activity activity, Point position) {

                int popupWidth = 120;
                int popupHeight = 130;

                LinearLayout linearLayout = (LinearLayout) findViewById(R.id.popup);

                LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(LAYOUT_INFLATER_SERVICE);

                 popupView = layoutInflater.inflate(R.layout.popup, linearLayout);

                 popupWindow = new PopupWindow(activity);
                 popupWindow.setContentView(popupView);
                 popupWindow.setWidth(popupWidth);
                 popupWindow.setHeight(popupHeight);

                 int offset_X = 85;
                 int offset_Y = 5;

                 popupWindow.setBackgroundDrawable(new BitmapDrawable());
                 popupWindow.showAtLocation(popupView, Gravity.NO_GRAVITY, position.x + offset_X, position.y + offset_Y);

            }
        });     
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus){

        int[] location = new int[2];
        buttonBrowse.getLocationOnScreen(location);
        position = new Point();
        position.x = location[0];
        position.y = location[1];

    }

    public void buttonGallery_Click(View v){

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

    public void buttonTakePhoto_Click(View v){
        popupWindow.dismiss();
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA_REQUEST);
    }

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, 
               Intent intent){

        switch(requestCode) { 
        case REQ_CODE_PICK_IMAGE:
            if(resultCode == RESULT_OK){  
             Uri selectedImageUri = intent.getData();
               selectedImageRealPath = getRealPathFromURI(selectedImageUri);
               imageSelected = BitmapFactory.decodeFile(selectedImageRealPath);
               compressedImage = imageCompression(selectedImageRealPath);  

                final ImageView imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
               imageViewPhoto.setImageBitmap(imageSelected);

            }
            break;

        case CAMERA_REQUEST:
            if(resultCode == RESULT_OK){
                Uri selectedImageUri = intent.getData();
                selectedImageRealPath = getRealPathFromURI(selectedImageUri);
                imageSelected = (Bitmap) intent.getExtras().get("data");
                MediaStore.Images.Media.insertImage(getContentResolver(), imageSelected, String.valueOf(System.currentTimeMillis()), "This is an Image.");
                compressedImage = imageCompression(selectedImageRealPath);

                final ImageView imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
                imageViewPhoto.setImageBitmap(imageSelected);
            }
            break;
        }
        popupWindow.dismiss();  
    }


    private String imageCompression(String filePath) {
        File imageFile = new File(filePath);
        FileInputStream fis = null;

        try
        {
          fis = new FileInputStream(imageFile); 
        }
        catch(FileNotFoundException e)
        {
            e.printStackTrace();
        }

        Bitmap bm = BitmapFactory.decodeStream(fis);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 90, baos );

        byte[] b = baos.toByteArray();

        return Base64.encodeToString(b, Base64.DEFAULT);
}



    public String getRealPathFromURI(Uri contentUri)
    {
        try
        {
            String[] proj = {MediaStore.Images.Media.DATA};
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        catch (Exception e)
        {
            return contentUri.getPath();
        }
    }




}
4

4 回答 4

0
     Image ivcard = Base64ToImage(vcard);
    //Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
   // thumb.Save(Path.ChangeExtension(fileName, "thumb"));
    try
    {
        string x = System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
        string ipath1;
        ipath1 = "ma\\imagesc1" + x + ".jpg";

        ivcard.Save(Server.MapPath(ipath1), System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    catch { }



private Image Base64ToImage(string base64String)
{
    // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    using (MemoryStream ms = new MemoryStream(imageBytes, 0,
                                     imageBytes.Length))
    {
        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        Image image = Image.FromStream(ms, true);
        return image;
    }
}
于 2014-09-27T18:08:38.180 回答
0
public void uploadImage(String filePath) {

   File imgFile=new File(filePath);
    RequestParams requestParamsForUploadImage=new RequestParams();
    requestParamsForUploadImage.put("file",imgFile);        

    AsyncHttpClient client = new AsyncHttpClient();

    client.post("URL of server upload file",
            requestParamsForUploadImage, new JsonHttpResponseHandler() {
                // response code '200'
                @Override
                public void onSuccess(int statusCode, org.apache.http.Header[] headers, org.json.JSONObject response) {
                    //Image is uploaded successfully...
                }

                // When the response returned by REST has Http
                // response code other than '200' such as '404',
                // '500' or '403' etc
                @Override
                public void onFailure(int statusCode, org.apache.http.Header[] headers, java.lang.Throwable throwable, org.json.JSONObject errorResponse) {
                  //Failed to upload
                }

            });
}

因为我使用AsyncHttpClient库来执行文件上传。不要忘记将它添加到您的项目中

于 2015-03-04T09:38:12.667 回答
0
public  String EncodeToString(Bitmap image)
{                   
     Bitmap immagex=image;
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
     byte[] b = baos.toByteArray();
     String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);            
     return imageEncoded;
}

确保在将位图传递给此方法时尝试尽可能减小位图的大小,并尽可能在后台线程中运行

于 2013-01-28T12:01:26.687 回答
0

压缩图片到75%然后上传。

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 75, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
于 2016-01-27T05:52:47.087 回答