Conversion from file to bitmap in android

非 Y 不嫁゛ 提交于 2019-12-12 03:24:06

问题


Ok I have updated my question. This is my upload image to server project. Everything works fine no errors, but I keep getting files that are 10, 12 or 16 bytes. But with right name and type.

            public class MainActivity extends AppCompatActivity implements View.OnClickListener {



private int PICK_IMAGE_REQUEST = 1;

private Button buttonChoose;
private Button buttonUpload;
String attachmentName = "bitmap";
File f;
private ImageView imageView;
private Bitmap bitmap;
private Bitmap bit;
ByteArrayBody bitmapBody;
ContentBody contentPart;
private Uri filePath;
private String stringPath;
byte[] bitmapdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    int SDK_INT = android.os.Build.VERSION.SDK_INT;
    if (SDK_INT > 8) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        buttonChoose = (Button) findViewById(R.id.buttonChoose);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);

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

        buttonChoose.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }
}




 private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

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

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        filePath = data.getData();
        Log.d(""+filePath,"PATHHH");
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public void getStringImage(){
    try {

    stringPath = getRealPathFromUri(getApplicationContext(), filePath);
     f = new File(stringPath);
     Log.d("FAJLEE" + f, "2");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100 /*ignored for png*/ , bos);
    byte[] bitmapdata = bos.toByteArray();
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(bitmapdata);
        fos.flush();
        fos.close();

        } catch (Exception e) {
          e.printStackTrace();
            Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
        }
    }





public static String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }



 public void uploadImage(){
 try {
     Log.d("Stefna ", "ajdbarovde");
     DefaultHttpClient httpclient = new DefaultHttpClient();
     InputStream responseStream = null;
     String responseString = "";
     try {
         HttpPost httppost = new HttpPost("http://studentskioglas.com/aplikacija/upload.php");

           BitmapFactory.Options bmOptions = new BitmapFactory.Options();
             bit = BitmapFactory.decodeFile(f.getAbsolutePath(), bmOptions);
             //   bit = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length, bmOptions);
             Log.d("Usao u fajlee","");

         HttpEntity reqEntity = MultipartEntityBuilder.create()
                 .addBinaryBody("bitmap", bitmapdata, ContentType.create("image/jpg"), f.getName())
                 .build();
         Log.d("Stefan ", f+"FAJLEEE");

         httppost.setEntity(reqEntity);

         System.out.println("executing request " + httppost.getRequestLine());
         HttpResponse response = httpclient.execute(httppost);Log.d("Stefan", "ispod");
         try {
             System.out.println("----------------------------------------");
             System.out.println(response.getStatusLine());
             HttpEntity resEntity = response.getEntity();
             if (resEntity != null) {
                 Log.d("Response content l: " + resEntity.getContentLength(), "");

                 responseStream = resEntity.getContent();
                 if (responseStream != null) {
                     BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                     String responseLine = br.readLine();
                     String tempResponseString = "";
                     while (responseLine != null) {
                         tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator");
                         responseLine = br.readLine();
                     }
                     br.close();
                     if (tempResponseString.length() > 0) {
                         responseString = tempResponseString;
                         Log.d(""+responseString,"");
                     }
                 }

             }

         } finally {
             response = null;
         }
     } finally {
         httpclient = null;
     }
 } catch (Exception e) {
     e.printStackTrace();
 } } 

 @Override
public void onClick(View v) {
    if (v == buttonChoose) {
        showFileChooser();
    }
    if(v == buttonUpload){
        getStringImage();
        uploadImage();
        imageView.setImageBitmap(bit);
    }

My paths look fine. First I thought that problem lays down in bitmap to file conversion but it doesn't. So I've tried to convert it back to see if there is some malfunction I've removed AsyncTask and now I can see image converted back from file so I know that I'm sending good file with proper size and every parameters. But on server I got small files that when I download can't see. This is my PHP script on server side.

<?php

$target_path = "images/";

$target_path = $target_path . basename( $_FILES['bitmap']['name']); 

if(file_put_contents($target_path, $_FILES['bitmap']['name'])) {


echo "The file ".  basename( $_FILES['bitmap']['name']).

" has been uploaded";

} else{
echo "There was an error uploading the file, please try again!";
} ?>

Just to update I have found the answer. Error was in file_put_contents it should be move_uploaded_file but with $_FILE['your tag']['tmp_name']. Don't get confused to change it to $_FILE['your tag']['name'] because ['tmp_name'] is the name of your file in that particular moment and it is name that server sees.


回答1:


I usually use the helper methods below that works quite well. Give them a try.

public static Bitmap convertBLOB2Bitmap(byte[] blob) {
    Options options = new BitmapFactory.Options();
    Bitmap tmp = BitmapFactory.decodeByteArray(blob, 0, blob.length, options);
    return tmp;
}


public static byte[] convertBitmap2BLOB(Bitmap bitmap) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
    return bos.toByteArray();
}



回答2:


use this code

File imgFile = new  File(selectedImageUrl);
            if(imgFile.exists()){
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}


来源:https://stackoverflow.com/questions/33275893/conversion-from-file-to-bitmap-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!