使用Android

时间:2016-04-20 08:25:36

标签: php android bitmap

我使用“Android Studio”构建一个Android应用程序,在压缩后上传图像并使用base64对其进行编码,并以字符串格式将其保存在服务器上,然后下载(PHP使用JSON发送图像字符串)。解码图像后,某些图像正常显示,但其他图像不显示(大多数图像不显示)。

我搜索并尝试了许多已发布的解决方案,但没有任何正常工作,请任何帮助。

这是我的android java代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private static final int RESULT_LOAD_IMAGE = 1;

ImageView imagetoupload, imagetodownload;
Button up_bt, dw_bt;
EditText etuploadname, etdownname;
String get_etdownname, down_user_pic, encodedImage;
Bitmap decodedByte;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imagetoupload = (ImageView) findViewById(R.id.imagetoupload);
    imagetodownload = (ImageView) findViewById(R.id.imagetodownload);

    up_bt = (Button) findViewById(R.id.up_bt);
    dw_bt = (Button) findViewById(R.id.dw_bt);

    etuploadname = (EditText) findViewById(R.id.etuploadname);
    etdownname = (EditText) findViewById(R.id.etdownname);

    up_bt.setOnClickListener(this);
    dw_bt.setOnClickListener(this);
    imagetoupload.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.imagetoupload:

            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);

            break;

        case R.id.up_bt:

            Bitmap image = ((BitmapDrawable) imagetoupload.getDrawable()).getBitmap();
            new UploadImage(image, etuploadname.getText().toString()).execute();

            break;

        case R.id.dw_bt:

            get_etdownname = etdownname.getText().toString();
            DownloadBackGround b = new DownloadBackGround();
            b.execute(get_etdownname);

            break;
    }
}

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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
        Uri selectedimage = data.getData();
        imagetoupload.setImageURI(selectedimage);
    }
}

private class UploadImage extends AsyncTask<Void, Void, Void> {

    Bitmap image;
    String name;

    public UploadImage(Bitmap image, String name) {
        this.image = image;
        this.name = name;
    }

    @SuppressWarnings("ResourceType")
    @Override
    protected Void doInBackground(Void... params) {

        String data = "";
        int tmp;

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);

        encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
        Log.d("Me", encodedImage);

        try {
            URL url = new URL("------ my url -------");
            String urlParams = "image=" + encodedImage + "&name=" + name;

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);

            OutputStream os = httpURLConnection.getOutputStream();
            os.write(urlParams.getBytes());
            os.flush();
            os.close();

            InputStream is = httpURLConnection.getInputStream();
            while ((tmp = is.read()) != -1) {
                data += (char) tmp;
            }
            is.close();

            httpURLConnection.disconnect();

            Log.e("Me", data + "");

            //  return data;

        } catch (IOException e) {
            e.printStackTrace();
            // return "Exception: " + e.getMessage();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Toast.makeText(getApplicationContext(), "image uploaded", Toast.LENGTH_LONG).show();


        byte[] decodedString = Base64.decode(encodedImage.getBytes(), Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        imagetodownload.setImageBitmap(decodedByte);

        imagetodownload.setImageBitmap(decodedByte);
    }
}


////////////////////////////download /////////////////////////////

class DownloadBackGround extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        String name_pic = params[0];

        try {
            URL url = new URL("------ my url ------");
            String urlParams = "name=" + name_pic;

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);

            OutputStream os = httpURLConnection.getOutputStream();
            os.write(urlParams.getBytes());
            os.flush();
            os.close();

            InputStream is = httpURLConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder buffer = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            is.close();
            httpURLConnection.disconnect();

            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "Exception: " + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "Exception: " + e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result.equals("2")) {
            Log.e("Me", "No picture in this name");
        } else {
            Log.e("Me", result);

            try {
                JSONObject parentObject = new JSONObject(result);
                JSONArray parentArray = parentObject.getJSONArray("result");

                JSONObject finalObject = parentArray.getJSONObject(0);

                down_user_pic = finalObject.getString("pic_byte");

            } catch (JSONException e) {
                e.printStackTrace();
            }

            //// decode picture and set here

            Log.d("Me", down_user_pic);

            byte[] decodedString = Base64.decode(down_user_pic.getBytes(), Base64.DEFAULT);
            decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
            imagetodownload.setImageBitmap(decodedByte);

        }
    }
}

///////////////////////////////下载/////////////// ///////////

这是我上传的php代码:

       <?php require "init.php";

      // Check connection

      if (!$con) {
       die("Connection failed: " . mysqli_connect_error());
       }

     $image = $_REQUEST["image"];
     $name = $_POST["name"];
     $image = str_replace(" ", "+", $image);
     $id= uniqid();
     //$decodedImage = base64_decode("$image");

    $sql = "INSERT INTO `pictures` (`id`, `pic_id`, `pic_byte`) VALUES          ('".$id."', '".$name."', '".$image."');";     
   if(!mysqli_query($con, $sql)){
    }
     ?>

这是我下载的PHP代码:

<?php
require "init.php";

// Check connection

if (!$con) {
     die("Connection failed: " . mysqli_connect_error());
}

$name = $_POST["name"];

$id= uniqid();


$sql = "SELECT * FROM pictures WHERE `pic_id`='".$name."'";

$res = mysqli_query($con,$sql); 
$result = array();

while($row = mysqli_fetch_array($res)){   
      array_push($result,
      array('pic_byte'=>$row[2])); 
      }

$string1 = '{"result":[]}';
$string2 = json_encode(array("result"=>$result));

$pos = strspn($string1 ^ $string2, "\0");

if($string1[$pos]=="" && $string2[$pos] == ""){  
             echo "2";
            }else {
            echo $string2;
            } 

?>

这个logcat显示:

   04-20 11:39:31.184 18472-18472/com.example.aly.updownpic D/dalvikvm: GC_FOR_ALLOC freed 1765K, 44% free 7473K/13340K, paused 17ms, total 21ms
    04-20 11:39:31.184 18472-18472/com.example.aly.updownpic I/dalvikvm-heap: Grow heap (frag case) to 13.192MB for 4080016-byte allocation
    04-20 11:39:31.234 18472-18472/com.example.aly.updownpic D/skia: --- decoder->decode returned false

更新

我使用的是JPEG,但不到一半的图片显示

this is the screenshot of the picture

0 个答案:

没有答案