Php android中文件到位图的转换

Php android中文件到位图的转换,php,android,file,bitmap,server,Php,Android,File,Bitmap,Server,好的,我已经更新了我的问题。这是我的上传图像到服务器项目。一切正常,没有错误,但我一直得到10、12或16字节的文件。但名称和类型正确 public class MainActivity extends AppCompatActivity implements View.OnClickListener { private int PICK_IMAGE_REQUEST = 1; private Button buttonChoose; private Button

好的,我已经更新了我的问题。这是我的上传图像到服务器项目。一切正常,没有错误,但我一直得到10、12或16字节的文件。但名称和类型正确

            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脚本

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

只是为了更新我已经找到了答案。文件内容中出现错误,应将其移动到上传的文件中,但使用$文件['your tag']['tmp\u name']。将其更改为$_FILE['your tag']['name']时不要感到困惑,因为['tmp_name']是您在特定时刻的文件名,也是服务器看到的名称

使用此代码

File imgFile = new  File(selectedImageUrl);
            if(imgFile.exists()){
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
使用此代码

File imgFile = new  File(selectedImageUrl);
            if(imgFile.exists()){
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
使用此代码

File imgFile = new  File(selectedImageUrl);
            if(imgFile.exists()){
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
使用此代码

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

我通常使用下面的helper方法,效果很好。试试看

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

我通常使用下面的helper方法,效果很好。试试看

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

我通常使用下面的helper方法,效果很好。试试看

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

我通常使用下面的helper方法,效果很好。试试看

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



谢谢,但它不起作用。他在“如果”中选择任意一种方式,但不转换回图像@Ravneet SinghProblem与AsyncTask在一起@Ravneet SinghThank的,但它不起作用。他在“如果”中选择任意一种方式,但不转换回图像@Ravneet SinghProblem与AsyncTask在一起@Ravneet SinghThank的,但它不起作用。他在“如果”中选择任意一种方式,但不转换回图像@Ravneet SinghProblem与AsyncTask在一起@Ravneet SinghThank的,但它不起作用。他在“如果”中选择任意一种方式,但不转换回图像@Ravneet SinghProblem与AsyncTask在一起@Ravneet SinghThank谢谢你。我原以为这会对我有帮助,但事实并非如此。我不知道为什么@Florian Barthme可能的问题是,
onActivityResult
您没有得到正确的图像?但我得到了,因为当我在imageView中放入变量“bitmap”时,一切正常@Florian BarthIt可以很好地处理您的代码和我的原始代码,问题是我将代码放在AsyncTask函数中,所以我的变量位没有初始化@弗洛里安·巴特谢谢你。我原以为这会对我有帮助,但事实并非如此。我不知道为什么@Florian Barthme可能的问题是,
onActivityResult
您没有得到正确的图像?但我得到了,因为当我在imageView中放入变量“bitmap”时,一切正常@Florian BarthIt可以很好地处理您的代码和我的原始代码,问题是我将代码放在AsyncTask函数中,所以我的变量位没有初始化@弗洛里安·巴特谢谢你。我原以为这会对我有帮助,但事实并非如此。我不知道为什么@Florian Barthme可能的问题是,
onActivityResult
您没有得到正确的图像?但我得到了,因为当我在imageView中放入变量“bitmap”时,一切正常@Florian BarthIt可以很好地处理您的代码和我的原始代码,问题是我将代码放在AsyncTask函数中,所以我的变量位没有初始化@弗洛里安·巴特谢谢你。我原以为这会对我有帮助,但事实并非如此。我不知道为什么@Florian Barthme可能的问题是,
onActivityResult
您没有得到正确的图像?但我得到了,因为当我在imageView中放入变量“bitmap”时,一切正常@Florian BarthIt可以很好地处理您的代码和我的原始代码,问题是我将代码放在AsyncTask函数中,所以我的变量位没有初始化@Florian BarthIf
uploadImage()
AsyncTask
然后在
bit
变量初始化之前调用
imageView.setImageBitmap(bit)
。但这很难说,因为您发布的代码片段并不能完整地描述正在发生的事情。您做得非常好。那真是我的问题。所以我已经删除了异步任务,现在我看到了图片。所以这不是我的问题。现在我确信我传递了良好的形象。但为什么我在服务器上读取的文件如此之小?它们不是0字节@Dalija Prasnikar检查发送到服务器的
位图数据的大小,并将其与服务器上的大小进行比较。如果存在差异,则在发送/检索代码时出错,如果没有,则您的
bitmapdata
包含错误的数据。很少观察到,您将bitmapdata编码为PNG,并将其作为image/jpg发送到服务器。接下来,如果您喜欢使用成员变量,请使用返回结果的函数-
getStringImage
就是一个很好的例子。使用成员字段会使跟踪代码中发生的事情变得更加困难。在不同的文件和位图之间加载和保存图像也太多了,除了将文件上传到服务器之外,我很难理解您想要做什么。我的位图数据是16,就像我在服务器上得到的一样,但我不知道为什么?我使用了Log.d(“DA”,“bm size:+bitmap.getByteCount()/1024”)代码;Log.d(“DAA”,“baos size:+bos.size()/1024”);Log.d(“DAAA”,“字节大小:”+bitmapdata.length/1024);第一个记录987其他两个记录16但为什么@Dalija Prasnikar如果
uploadImage()
AsyncTask
,则在
bit
变量初始化之前调用
imageView.setImageBitmap(bit)
。但这很难说,因为您发布的代码片段并不能完整地描述正在发生的事情。您做得非常好。那真是我的问题。所以我已经删除了异步任务,现在我看到了图片。所以这不是我的问题。现在我确信我传递了良好的形象。但为什么我在服务器上读取的文件如此之小?它们不是0字节@Dalija PrasnikarCheck
位图数据的大小