There are answers on SO about converting an image to a JPEG using PHP’s imagejpeg
and either displaying in browser or saving to disk such as this one but I can’t find way to convert to JPEG without displaying or saving so it merely stays in memory without the extra overhead of saving to disk or displaying.
The use case is that the code is in an API endpoint that receives a request from a mobile device, sends a request to one API that returns a PNG file in the form of a string and then must send a JPEG file to a second API that only accepts JPEG files before returning the final result to the user.
While accomplishing these tasks, time is of the essence. Displaying the image in a background thread would be absurd and a waste of resources as would saving it to disk. All I need to do is convert the PNG file to a JPEG file but imagejpeg
seems to have the added behavior of outputting the image or saving it.
The code where I receive the image as a PNG string and then must convert it into a JPEG image is;
$response = "xxx"; //png image from an API in the form of string
$image = imagecreatefromstring($response);//convert to in memory image. this line of code works perfectly
imagejpeg($image);//This converts to jpeg and displays file in browser--this displays to browser. I don't want to display it
imagejpeg($image, 'output.jpg', 100); // variation of imagejpeg that saves the file to disk same as imagejpeg($image)--I don't want to save it to disk
imagejpeg($image, NULL,100);//displays to browser. This is the top-voted but not accepted answer in question linked to.
Does imagejpeg have an option to simply change png to jpeg without displaying in a browser or saving to disk?
Note this has nothing to do with compressing files or with converting the image file into a string as in the question referenced. That question is about turning an image into a string. My situation is the exact opposite; I receive the image as a string from the first API and convert it to a file in memory without a problem using imagecreatefromstring($response)
.
My question is how to convert the PNG image to JPEG efficiently within my API. I don’t want the script to time out or waste resources or possibly crash due to unnecessary activity such as displaying or saving to disk.