Skip to content
Advertisement

How do I reduce image size in php?

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;

    }
}

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement