Send Images to Api / Server

Send Images to Api / Server

Convert Image To String To Send in API to Server Database:

  • In Order to send images to api it need to send in Base64 Encoded String Format
  • Than it will be decoded on server and converted to image and store on server / database

Follow this Steps to Convert Image to String

  1. Convert Image to Drawable
  1. convert to BitmapDrawable
  1. convert to Bitmap
  1. Create ByteArrayOutputStream
  1. compress bitmap
  1. convert to ByteArray / Byte[]
  1. Encode to String Using Base64 Format
 
// Convert Single image to String From ImageView fun imageToString(): String { val imgDrawable = pImage.drawable val bitmap = (imgDrawable as BitmapDrawable).bitmap val stream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream) val byteArray = stream.toByteArray() return Base64.encodeToString(byteArray, Base64.DEFAULT) }
 
// Convert Img Uri to String private fun uriToString(selectedFileUri: Uri): String { val bitmap = MediaStore.Images.Media.getBitmap(activity.contentResolver, selectedFileUri) val stream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream) val byteArray = stream.toByteArray() return Base64.encodeToString(byteArray, Base64.DEFAULT) }
 

PHP Server side implementation

  • than this String are sent to api with parameters
// For Single Encoded Image <?php ... // get encoded String $pimag64 = $_POST['pthumbnail']; // generate Image name to save this image with path and format $imgname = "ProductsImages/"."Image".rand(10000,99999).rand(10000,99999).".jpg"; // decode encoded String $Image = base64_decode($pimg64); // store image to given path file_put_contents($imgname, $Image); ... ?>
// For Array Or List of Encoded Images <?php ... // get encoded Image List $imgdata = $_POST['imgdata_list']; // Toatl Image count $total_img = $_POST['total_images']; // Convert to int if its in String $listsize = (int)$total_img; // explode remove "," and convert to " " from encoded String List Of Images $imagelist = explode(",",$imgdata); // loop to process each Image String for($i = 0; $i<$listsize; $i++){ $imgname = "ProductsImages/"."Image".rand(10000,99999).rand(10000,99999).".jpg"; $Image = base64_decode($imagelist[$i]); file_put_contents($imgname, $Image); // add all image name with path to list $imgn[$i] = $imgname; $pThumbnail = $imgname; } // implode convert " " to "," to create list of images path to store in database $imagelist2 = implode(",",$imgn); ... ?>