0

I am using a PHP file as an API to upload photos to my app but the images are uploaded in a big size I need to reduce the image size but keep a good quality

I am using this code to upload photos

$imagearray =  json_decode($_POST['img']);

 foreach($imagearray as $value){

    $data = explode(',', $value);

    $imagedata = base64_decode($data[1]);

    $nam =  genRandomString().'.jpeg';

    $target_path='../uploads/'.$nam;

    file_put_contents($target_path,$imagedata);

    if($imgsname=="")

    {

    $imgsname=$nam;

    $imgname=$nam;

    }

    else

    {

    $imgsname=$imgsname.','.$nam;

    }
}
palaѕн
  • 72,112
  • 17
  • 116
  • 136
iphone acc
  • 15
  • 1
  • 4
  • You need to explain better what you are trying to achieve. Is that PHP file part of the APP you're uploading the images to? or is it just some kind of middleware to shrink the images? – Itai Bar-Haim May 12 '20 at 13:43

1 Answers1

1

First of all hello welcome. Please search before asking questions first.


If you are looking to reduce the size using coding itself, you can follow this code in php.

<?php

function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);

    return $destination;
}

$source_img = 'source.jpg';
$destination_img = 'destination .jpg';

$d = compress($source_img, $destination_img, 90);
?>

$d = compress($source_img, $destination_img, 90);

This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source);

The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.

Referrer : Which is the best PHP method to reduce the image size without losing quality

Özgür Can Karagöz
  • 1,039
  • 1
  • 13
  • 32