1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.