Image compression without changing the content format (png, jpeg, gif, webp)

2

The difference between this question and duplicates: keep the format of the content (png, jpeg, gif, webp) in order not to harm images with layers, transparency, etc. The others do not.

I have a file upload script , where I save the file to a folder, and write to the database the address:

if (!empty($_FILES['anexo']['name']) && ($fass[0]['status'] != 'C' && $fass[0]['status'] != 'F'))
{
        $arqNome = $_FILES['anexo']['name'];
        $extpat  = pathinfo($_FILES['anexo']['name']);
        $ext     = $extpat['extension'];

        $uploaddir  = $_SERVER['DOCUMENT_ROOT'].'/sys/files/';
        $uploadfile = $tId . '-' . time();
        $uploadatt  = $uploaddir . $uploadfile . '.' . $ext;

        if (move_uploaded_file($_FILES['anx']['tmp_name'], $uploadatt)) 
        {
            $dir = str_replace('\', '\\', $uploaddir);
            $arq = $uploadfile;
            $att = $arq . '.' . $ext; // $dir

            if ($attc -> attachments($tId,$arqNome,$att,$solicitante))
            {
                header('location:../t_vis.php?id='. $tId);
            }
        }
}

I've been scanning, and have images attachments that are very large .

I would like to "compress / shrink" the image, for example Whatsapp does, but of course, without losing image quality, keeping file type (jpg, png, etc), so it does not "spoil" the original image with loss of layers, transparency, etc.

  • Are there any native functions for this purpose?
  • Are there libraries?
  • Are there other ways?
asked by anonymous 10.07.2018 / 15:50

1 answer

2

Just use for each image the functions for each format:

For PNG

For JPEG

For GIF

For WEBP (requires PHP 5.4 +)

There are other clear formats, such as BMP and WBMP, but they are not good formats to work with WEB, since it usually does not have compression which makes a simple image quite heavy.

Working without losing transparency

Using imagecreatefrompng can cause loss of transparency, so to avoid loss use:

imagealphablending (resource $image , true);
imagesavealpha (resource $image , true);

An example code to reduce images with PHP in different formats

Following the example of calculating the @Bacco response:

<?php
function image_resize($path, $width = 200, $height = 200, $save = null, $quality = 100)
{
    $details = getimagesize($path);

    if (!$details) {
        trigger_error('Imagem inválida');
        return false;
    }

    $width_orig = $details[0];
    $height_orig = $details[1];

    // Calculando a proporção
    $ratio_orig = $width_orig / $height_orig;

    if ($width / $height > $ratio_orig) {
        $width = $height * $ratio_orig;
    } else {
        $height = $width / $ratio_orig;
    }

    if (is_string($save) === false) {
        $save = null;
        header('Content-Type: ' . $details['mime']);
    }

    $image_p = imagecreatetruecolor($width, $height);

    switch ($details['mime']) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($path);
            break; 
        case 'image/gif': 
            $image = imagecreatefromgif($path);
            break; 
        case 'image/png': 
            $image = imagecreatefrompng($path);
            break;
        case 'image/webp': 
            $image = imagecreatefromwebp($path);
            break;
        default:
            trigger_error('Formato não suportado');
            $image_p = null;
            return false;
    }

    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    if ( in_array($details['mime'], array('image/png', 'image/webp')) ) {
        imagealphablending($image_p, true);
        imagesavealpha($image_p, true);
    }

    switch ($details['mime']) {
        case 'image/jpeg':
            imagejpeg($image_p, $save, $quality);
            break; 
        case 'image/gif': 
            imagegif($image_p, $save);
            break; 
        case 'image/png': 
            imagepng($image_p, $save, $quality);
            break;
        case 'image/webp': 
            imagewebp($image_p, $save, $quality);
            break;
    }
}

Example usage for copying a JPEG image to a new child:

image_resize('bar.jpg', 200, 200, 'bar_1.jpg');

To overwrite an image, just use the same name:

image_resize('bar.jpg', 200, 200, 'bar.jpg');

The first% wc of% would be the maximum width, and the second would be the maximum height.

    
10.07.2018 / 20:20