准备方法Base64格式图像用一组标准图像大小设置大小来编写php服务器
Bitmap bm = Bitmap.createScaledBitmap(MediaStore.Images.Media.getBitmap(getContentResolver(), filePath), sizeW, sizeH, true)
答案 0 :(得分:1)
int sizeW=MediaStore.Images.Media.getBitmap(getContentResolver(), filePath).getWidth();
int sizeH=MediaStore.Images.Media.getBitmap(getContentResolver(), filePath).getHeight();
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0,sizeW, sizeH), new RectF(0, 0, 300, 100), Matrix.ScaleToFit.FILL);
Bitmap bm = Bitmap.createBitmap(MediaStore.Images.Media.getBitmap(getContentResolver(), filePath), 0, 0, sizeW, sizeH, m, true);
//Bitmap bm = Bitmap.createScaledBitmap(MediaStore.Images.Media.getBitmap(getContentResolver(), filePath), sizeW, sizeH, true);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
//Log.d("size200",String.valueOf((bm.getByteCount()/1024)/2));
ba1 = Base64.encodeToString(ba, Base64.DEFAULT);
Log.e("base64-1", "-----" + ba1);
AsyncTask类:
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(RegisterAds.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("send");
pd.show();
}
@Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop" + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
Log.d("nameimage", String.valueOf(name_image_upload_i1));
new SummaryAsyncTask().execute((Void) null);
pd.dismiss();
}
}
使用:
new uploadToServer().execute();
php代码:
<?php
//error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$save_path=$_SERVER['DOCUMENT_ROOT']."/news/upload/".$imgname; //.$data;
header("Content-Type: bitmap; charset=utf-8");
$fp = fopen($save_path, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
echo "Image uploaded";
}else{
echo "Error uploading image";}}
?>
答案 1 :(得分:0)
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
return imageEncoded;
}