我有一个图像视图,我在其中设置图像,然后单击该图像发送到服务器。我该怎么做?
问问题
1663 次
1 回答
0
添加库ٰVolley
compile 'com.android.volley:volley:1.0.0'
和 AndroidManifest.xml 中的权限网
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PROFILE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
拍摄imageview的照片并将其转换为字符串
ImageView ivImage1 = (ImageView ) findViewById(R.id.img_add1_send );
String mmm=getStringImage( ( ( BitmapDrawable ) ivImage1.getDrawable( ) ).getBitmap( ) );
将照片功能转换为字符串
public String getStringImage(Bitmap bm){
ByteArrayOutputStream ba=new ByteArrayOutputStream( );
bm.compress( Bitmap.CompressFormat.PNG,90,ba );
byte[] by=ba.toByteArray();
String encod= Base64.encodeToString( by,Base64.DEFAULT );
return encod;
}
并将字符串转换为 JSON
JSONObject requestJsonObject = new JSONObject( );
requestJsonObject.put( "image", mmm );
我们使用以下函数将 JSON 发送到服务器
JsonObjectRequest jjj = new JsonObjectRequest( Request.Method.POST,
"http://192.168.16.1/dashbDoard/wDaryounes/GetDShopDDDBojId.php", requestJsonObject,
new Response.Listener< JSONObject >( ) {
@Override
public void onResponse( JSONObject response ) {
if ( response == 1 ) {
Toast.makeText( getApplication(), "yessss", Toast.LENGTH_SHORT ).show( );
} else {
Toast.makeText( getApplication(), "no", Toast.LENGTH_SHORT ).show( );
}
},new Response.ErrorListener( ) {
@Override
public void onErrorResponse( VolleyError error ) {
}
} );
jjj.setRetryPolicy( new DefaultRetryPolicy( 18000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT ) );
Volley.newRequestQueue( G.context ).add( jjj );
}
在服务器上,很容易把这个字符串变成照片
代码 php
$image = $_POST['image'];
$decodedImage = base64_decode($image);
$location = "img/" . $title . "_" . rand(rand(5, 50), rand(500, 900)) .
"_" . date("i") . "_" . date("d-m-Y") . ".jpg";
$resultOfCreatingImage = file_put_contents($location, $decodedImage);
if ($resultOfCreatingImage == false) {
$error['error'] = "failure_creating_image";
} else {
$q = "INSERT INTO ads( image) VALUES(?)";
$res = $connect->prepare($q);
$res->execute([$location]);
if ($res->rowCount() > 0) {
return 1;
} else {
return 0;
}
}
于 2017-08-22T18:12:44.550 回答