Jerome
Jerome

Reputation: 31

IOS Swift UIImage in base64 String to PHP

I am developing an application by Swift for Iphone / Ipad. It is an adaptation of an Android application. Problem is : I have a UIImage I resized. I want to convert this to a String to send a request on a PHP server. I have already made in Android

public static String BitMapToString(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String temp = Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

The String returned is read and stored as image in the server for PHP script:

$lienphoto = "adressesurleserveur".$nomimage;
$binary=base64_decode($image);
$fichier = fopen($lienphoto, 'wb');
fwrite($fichier, $binary);
fclose($fichier);

I want to do the same with swift, I have already tried:

var imageData = UIImageJPEGRepresentation(imageChoisie, 1.0)
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

and base64String correspond to String that PHP receives. This does not work, the created file is "corrupted". I try other ways for a few hours but I have no solution yet. I found no forums posts with a response to this problem.

In advance thank you for the time you will grant me.

Upvotes: 2

Views: 1476

Answers (1)

Jerome
Jerome

Reputation: 31

I found a solution.

The amendment is made in the php script:

 $lienphoto = "adresse sur serveur".$nomimage;

$data = str_replace('data:image/jpg;base64,', '', $image);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

$success = file_put_contents($lienphoto, $data);

This approach is proposed on the site:

http://www.tricksofit.com/2014/10/save-base64-encoded-image-to-file-using-php

This keeps the Swift and Android code. I just have to create two php scripts for saving the image.

Upvotes: 1

Related Questions