I build an android application using "Android Studio" that upload images after compress and encode it using base64 and save it at server in string format, then download it (PHP send images strings using JSON). after decoding the image some image is showing normally but other not (the most images doesn't appear).
I search and try many posted solution, but nothing worked properly, please any help.
this is my android java code:
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);
}
}
}
///////////////////////////////Download //////////////////////////
and this is my uploading php code:
<?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)){
}
?>
and this is my downloading php code:
<?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;
}
?>
this logcat was show:
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
UPDATE
I used JPEG but less than half of the picture is show