从文件转换到Android中位图 [英] Conversion from file to bitmap in android

查看:185
本文介绍了从文件转换到Android中位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我已经更新了我的问题。这是我上传图像服务器项目。一切正常没有任何错误,但我一直是10,12或16字节获取文件。但随着权的名称和类型。

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

我的路径看起来很好。首先,我认为这个问题规定了在位图文件的转换,但事实并非如此。所以,我试着将其转换回,看看是否有一些故障我已删除的AsyncTask,现在我可以看到图像从文件转换回所以我知道我要送好文件,合适的大小和每一个参数。但在服务器上我的小文件,当我下载看不到。这是我在服务器端的PHP脚本。

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!";
} ?>

只是为了更新我已经找到了答案。错误是的file_put_contents应该move_uploaded_file但$ _FILE ['您的标记'] ['tmp_name的值。不要混淆将其更改为$ _FILE ['您的标记'] ['名称'],因为['tmp_name的值']在特定的时刻你的文件的名称,它是命名的服务器发现。

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.

推荐答案

我通常使用的辅助方法低于工作得很好。给他们一个尝试。

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

这篇关于从文件转换到Android中位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆