dongyong3223
dongyong3223
2017-10-15 11:38
浏览 78

在Xamarin C中将图像从android上传到php服务器#

Im trying to upload images from Android app to Php Server . I found way to upload the image by encode it as base64 using c# and decode it again using php base64 decoder . Everything working well i can upload the image to the server successfully but after i upload it, the images dose not open using any image viewer i got this error

couldn't open this file

it just works inside the chrome or edge internet explorer or any other internet explorer. I hope you could help me to open it using image viewer like windows images viewer my c# code is like :

public override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
    {
        Stream stream = Activity.ContentResolver.OpenInputStream(data.Data);
        Bitmap bitmap = BitmapFactory.DecodeStream(stream);
        MemoryStream memStream = new MemoryStream();
        bitmap.Compress(Bitmap.CompressFormat.Webp, 100, memStream);
        byte[] picData = memStream.ToArray();
        WebClient client = new WebClient();
        Uri uri = new Uri(statics_class.request_url+"request.php");
        NameValueCollection parameters = new NameValueCollection();
        parameters.Add("Image", Convert.ToBase64String(picData));
        parameters.Add("Image_id", image_id.ToString());
        parameters.Add("user_id", user_id);
        client.UploadValuesAsync(uri, parameters);
        client.UploadValuesCompleted += Client_UploadValuesCompleted;
    }
} 

And my php code :

if (isset($_POST['Image']) && isset($_POST['Image_id']) && isset($_POST['user_id']))

{

    $user_id = $_POST['user_id'] ; 
    $Image_id = $_POST['Image_id'] ; 
    $now = DateTime::createFromFormat('U.u',microtime(true));
    $id = $now->format('YmdHisu');
    $upload_folder = "upload/$user_id";
    if(!is_dir($upload_folder)){
        mkdir($upload_folder);
    }
    $path = "upload/$user_id/$id.jpg";

    $image = $_POST['Image'] ;


    if(file_put_contents($path , base64_decode($image)) != false){

            printf('<img src="data:image/jpg;base64,%s" />', $image);
        echo "successed ";
        exit;
    }else{
        echo "failed";
    }


}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanhanglekr37902
    duanhanglekr37902 2017-10-15 11:42
    已采纳

    Don't use Bitmap.CompressFormat.Webp, but Bitmap.CompressFormat.PNG (or jpeg if lossy photo compression is okay).

    WebP is a relatively new image format that is not widely supported yet.

    点赞 评论

相关推荐