Base64编码产品结果不同

时间:2016-10-25 05:03:39

标签: php android base64

我正在研究android项目,它可以从用户的手机galery上传图像。我用来上传图像的方法是将图像编码到android中的base64并将其发送到服务器上的PHP文件,然后PHP文件对其进行解码,然后将其放在服务器上。

但问题是PHP解码的结果与原始图像不同。虽然图像仍在工作,但我担心有时它会成为一个bug:D .. 怎么解决?

类UploadImageCatalog

@Override
protected String doInBackground(String... params) {
    String urlAPI = params[0];
    String id = params[1];
    String imageByte = params[2];
    try {
        URL url = new URL(urlAPI);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setReadTimeout(15000);
        urlCon.setConnectTimeout(15000);
        urlCon.setDoOutput(true);
        urlCon.setRequestMethod("POST");
        OutputStream os = urlCon.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
        BufferedWriter bw = new BufferedWriter(osw);
        String postData = URLEncoder.encode("id", "UTF-8")+"="+URLEncoder.encode(id, "UTF-8")+"&"+
                        URLEncoder.encode("imageByte", "UTF-8")+"="+URLEncoder.encode(imageByte, "UTF-8");
        bw.write(postData);
        bw.flush();
        bw.close();
        osw.close();
        os.close();
        urlCon.connect();
        int responseCode = urlCon.getResponseCode();
        if (responseCode == HTTP_OK) {
            InputStream is = urlCon.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String responseString = br.readLine();

            br.close();
            isr.close();
            is.close();

            return responseString;
         }
     } catch (IOException e) {
         e.printStackTrace();
     }

     return null;
 }

方法getStringImage()

private String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    return Base64.encodeToString(imageBytes, Base64.DEFAULT);
}

Mehthod上传图片

btSave.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (updateImage) {
            new UploadImageCatalog(ViewProductActivity.this)
                            .execute(SERVER_URL+"/project/katalogmukenalukis/uploadimage.php",
            String.valueOf(idToView), getStringImage(imageLoadedBitmap));
        } else {
            updateData();
        }
    }
});

uploadimage.php

<?php
    $id = $_POST['id'];
    $imageByte = $_POST['imageByte'];
    $target = __DIR__."/asset/".$id;
    if (file_exists($target)) {unlink($target);}
    if (file_put_contents($target, base64_decode($imageByte))) {
        echo json_encode(array("success" => true));
    } else {
        echo json_encode(array("success" => false, "message" => ""));
    }
?>

0 个答案:

没有答案