Jump to content

imagecreatefromjpeg() error help


Go to solution Solved by MDCode,

Recommended Posts

Hi, 

 

before posting this problem, I already tried googling and tried those possible solutions that could help but still failed.

I am having a problem with that PHP function

imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error:

based from what i found in google, some say, use

ini_set("gd.jpeg_ignore_warning", 1);

failed.

 

some say, use

init_set("memory_limit", -1)

still failed

 

I am sure that I am passing .jpg image, how come i keep on getting that error ?

any suggestions of what to do?

Edited by sasori
Link to comment
https://forums.phpfreaks.com/topic/292007-imagecreatefromjpeg-error-help/
Share on other sites

it's not a script..i have a alot of random images in my local storage that i usually use for testing ... here's the part of the code

                $fext = pathinfo($url, PATHINFO_EXTENSION);
                $tmp_name = date('His') . rand() . "." . $fext;
                $filename = $path .'/'. $tmp_name;
                $cont = @file_get_contents($url);
                $op = @fopen($filename, 'w+');
                @fwrite($op, $cont);
                @fclose($op);
                chmod($filename, 0777);
                $orientation = 999;
                $exif = null;
                if (strtolower($fext) == 'jpg' || strtolower($fext) == 'jpeg') {
                    try {
                        $exif = @exif_read_data($filename);
                    } catch (Exception $e) {
                        Yii::log($e->getMessage());
                    };
                    if (!empty($exif) && !empty($exif['Orientation'])) {
                        $orientation = $exif['Orientation'];
                    }
                    $img = imagecreatefromjpeg($filename);
Edited by sasori

Check the headers of the file.  The extension can be jpeg, but the headers are what gets checked.

it's a jpeg image...how come other jpegs are being read without problems at all?

 

here are the two images, the baby apparel is ok, but the knitted hat is causing that error I mentioned in this thread..

 

i'm not sure if this forum modified those files that i just attached in this reply

post-66825-0-20945000-1414080619_thumb.jpg

post-66825-0-25251300-1414080665_thumb.jpg

Edited by sasori
  • 10 years later...

I use the `Intervention` library as it make handling images easier.

Here's how to rotate an image

use Intervention\Image\ImageManager;

$image = (new ImageManager())->make('public/image.jpg')->rotate(45)->save('public/rotated_image.jpg');

and here's an upload script from my website that might help?

<?php
// Include the configuration file and autoload file from the composer.
require_once __DIR__ . '/../config/clearwebconfig.php';
require_once "vendor/autoload.php";
use Intervention\Image\ImageManagerStatic as Image;
// Import the ErrorHandler and Database classes from the clearwebconcepts namespace.
use clearwebconcepts\{
    ErrorHandler,
    Database,
    ImageContentManager,
    LoginRepository as Login
};

$errorHandler = new ErrorHandler();

// Register the exception handler method
set_exception_handler([$errorHandler, 'handleException']);

$database = new Database();
$pdo = $database->createPDO();
$checkStatus = new Login($pdo);

// To check for either 'member' or 'sysop'
if ($checkStatus->check_security_level(['sysop'])) {
    // Grant access
} else {
    // Access denied
    header('location: dashboard.php');
    exit();
}

function is_ajax_request(): bool
{
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}


$save_result = false;

if (($_SERVER['REQUEST_METHOD'] === 'POST') && isset($_FILES['image'])) {
    $data = $_POST['cms'];
    $data['content'] = trim($data['content']);
    $errors = array();
    $exif_data = [];
    $file_name = $_FILES['image']['name']; // Temporary file:
    $file_size = $_FILES['image']['size'];
    $file_tmp = $_FILES['image']['tmp_name'];
    $thumb_tmp = $_FILES['image']['tmp_name'];
    $file_type = $_FILES['image']['type'];
    $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));


    /*
     * Set EXIF data info of image for database table that is
     * if it contains the info otherwise set to null.
     */
    if ($file_ext === 'jpeg' || $file_ext === 'jpg') {

        $exif_data = exif_read_data($file_tmp);


        if (array_key_exists('Make', $exif_data) && array_key_exists('Model', $exif_data)) {
            $data['Model'] = $exif_data['Make'] . ' ' . $exif_data['Model'];
        }

        if (array_key_exists('ExposureTime', $exif_data)) {
            $data['ExposureTime'] = $exif_data['ExposureTime'] . "s";
        }

        if (array_key_exists('ApertureFNumber', $exif_data['COMPUTED'])) {
            $data['Aperture'] = $exif_data['COMPUTED']['ApertureFNumber'];
        }

        if (array_key_exists('ISOSpeedRatings', $exif_data)) {
            $data['ISO'] = "ISO " . $exif_data['ISOSpeedRatings'];
        }

        if (array_key_exists('FocalLengthIn35mmFilm', $exif_data)) {
            $data['FocalLength'] = $exif_data['FocalLengthIn35mmFilm'] . "mm";
        }

    } else {
        $data['Model'] = null;
        $data['ExposureTime'] = null;
        $data['Aperture'] = null;
        $data['ISO'] = null;
        $data['FocalLength'] = null;
    }

    $data['content'] = trim($data['content']);

    $extensions = array("jpeg", "jpg", "png");

    if (in_array($file_ext, $extensions, true) === false) {
        $errors[] = "extension not allowed, please choose a JPEG or PNG file.";
    }

    if ($file_size >= 58720256) {
        $errors[] = 'File size must be less than or equal to 42 MB';
    }

    /*
     * Create unique name for image.
     */
    $image_random_string = bin2hex(random_bytes(16));
    $image_path = 'assets/image_path/img-entry-' . $image_random_string . '-2048x1365' . '.' . $file_ext;
    $thumb_path = 'assets/thumb_path/thumb-entry-' . $image_random_string . '-600x400' . '.' . $file_ext;


    move_uploaded_file($file_tmp, $image_path);
    move_uploaded_file($thumb_tmp, $thumb_path);


    // Load the image
    $image = Image::make($image_path);

    // Resize the image
    $image->resize(2048, 1365, function ($constraint) {
        $constraint->aspectRatio();
        $constraint->upsize();
    });

    // Save the new image
    $image->save($image_path, 100);

    // Load the image with Intervention Image
    $image = Image::make($image_path);

    // Resize the image while maintaining the aspect ratio
    $image->resize(600, 400, function ($constraint) {
        $constraint->aspectRatio();
        $constraint->upsize();
    });

    // Save the thumbnail
    $image->save($thumb_path, 100);


    $data['image_path'] = $image_path;
    $data['thumb_path'] = $thumb_path;


    /*
     * If no errors save ALL the information to the
     * database table.
     */
    if (empty($errors) === true) {
        // Save to Database Table CMS
        $timezone = new DateTimeZone('America/Detroit'); // Use your timezone here
        $today = new DateTime('now', $timezone);
        $data['date_updated'] = $data['date_added'] = $today->format("Y-m-d H:i:s");
        $cms = new ImageContentManager($pdo, $data);
        $result = $cms->create();

        if ($result) {
            header('Content-Type: application/json');
            echo json_encode(['status' => 'success']);
            exit();
        }
    } else {
        if (is_ajax_request()) {
            // Send a JSON response with errors for AJAX requests
            header('Content-Type: application/json');
            echo json_encode(['status' => 'error', 'errors' => $errors]);
        }
    }

}

 

Edited by Strider64

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.