How to Convert All Images to Jpg

How can I convert all images to jpg?

Try this code: originalImage is the path of... the original image... outputImage is self explaining enough. Quality is a number from 0 to 100 setting the output jpg quality (0 - worst, 100 - best)

function convertImage($originalImage, $outputImage, $quality)
{
// jpg, png, gif or bmp?
$exploded = explode('.',$originalImage);
$ext = $exploded[count($exploded) - 1];

if (preg_match('/jpg|jpeg/i',$ext))
$imageTmp=imagecreatefromjpeg($originalImage);
else if (preg_match('/png/i',$ext))
$imageTmp=imagecreatefrompng($originalImage);
else if (preg_match('/gif/i',$ext))
$imageTmp=imagecreatefromgif($originalImage);
else if (preg_match('/bmp/i',$ext))
$imageTmp=imagecreatefrombmp($originalImage);
else
return 0;

// quality is a value from 0 (worst) to 100 (best)
imagejpeg($imageTmp, $outputImage, $quality);
imagedestroy($imageTmp);

return 1;
}

How to convert all images to JPG format in PHP?

Maybe it's not working with PNG because PNG only supports compression levels 0 to 9.

I'd also rather modify the behaviour based on MIME type, not extension. And I guess you're checking your POST user input before using it in code ;)

Here's my variant of the code:

$path = "../images/DVDs/";

$img = $path . $_POST['logo_file'];

if (($img_info = getimagesize($img)) === FALSE)
die("Image not found or not an image");

switch ($img_info[2]) {
case IMAGETYPE_GIF : $src = imagecreatefromgif($img); break;
case IMAGETYPE_JPEG : $src = imagecreatefromjpeg($img); break;
case IMAGETYPE_PNG : $src = imagecreatefrompng($img); break;
default : die("Unknown filetype");
}

$tmp = imagecreatetruecolor(350, 494);
imagecopyresampled($tmp, $src, 0, 0, intval($_POST['x']), intval($_POST['y']),
350, 494, intval($_POST['w']), intval($_POST['h']));

$thumb = $path . pathinfo($img, PATHINFO_FILENAME) . "_thumb";
switch ($img_info[2]) {
case IMAGETYPE_GIF : imagegif($tmp, $thumb . '.gif'); break;
case IMAGETYPE_JPEG : imagejpeg($tmp, $thumb . '.jpg', 100); break;
case IMAGETYPE_PNG : imagepng($tmp, $thumb . '.png', 9); break;
default : die("Unknown filetype");
}

For every filetype you want supported, you only have to add two lines of code.

convert images to jpg in a makefile which have various extensions

I would rather go with a separate rule for every file that needs to be converted as this helps in finding out whether there was an error or not and act accordingly. When doing everything in a loop like above a) any error is missed (and the source file gets deleted even when conversion failed) and b) it always regenerates all files no matter if it was needed or not.

My approach would be to get all the files with interesting extensions, generate target names and use a static pattern rule for each target file. I would also generate a warning if there are two or more input files that would result in the same target file as it was not clearly stated what should be done in this situation.

For example:

$ cat Makefile
RASTERFORMATS := [Pp][Nn][Gg] [GgTt][Ii][Ff]
IMGPATH := images

IMAGES_TO_CONVERT := $(foreach format,$(RASTERFORMATS),$(wildcard $(IMGPATH)/*.$(format)))
$(info Images to convert: $(IMAGES_TO_CONVERT))

IMAGES := $(sort $(addsuffix .jpg,$(basename $(IMAGES_TO_CONVERT))))
$(info Target images: $(IMAGES))

percent := %

.SECONDEXPANSION:
.DELETE_ON_ERROR:

$(IMAGES): %.jpg: $$(filter $$*$$(percent), $(IMAGES_TO_CONVERT))
$(if $(word 2,$^),$(warning Multiple sources for $@, generating from $<))
@echo "$< -> $@"
gm mogrify -background white -colorspace CMYK -density 1200 -format jpg $<
echo rm -f $< # Drop echo if really want to remove input file

.PHONY: figures2jpg
figures2jpg: $(IMAGES)

Given the following:

$ ls images/
image1.png image2.PNG image2.png image3.gif

Sample output is:

$ make figures2jpg
Images to convert: images/image2.png images/image2.PNG images/image1.png images/image3.gif
Target images: images/image1.jpg images/image2.jpg images/image3.jpg
images/image1.png -> images/image1.jpg
gm mogrify -background white -colorspace CMYK -density 1200 -format jpg images/image1.png
echo rm -f images/image1.png
rm -f images/image1.png
Makefile:16: Multiple sources for images/image2.jpg, generating from images/image2.png
images/image2.png -> images/image2.jpg
gm mogrify -background white -colorspace CMYK -density 1200 -format jpg images/image2.png
gm mogrify: Improper image header (images/image2.png).
Makefile:16: recipe for target 'images/image2.jpg' failed
make: *** [images/image2.jpg] Error 1

Note the warning for image2.jpg. It also demonstrates that an error will prevent from deleting input file. Another invocation will retry, but image1.jpg will not be generated again since it's already up to date.

$ make figures2jpg
Images to convert: images/image2.png images/image2.PNG images/image1.png images/image3.gif
Target images: images/image1.jpg images/image2.jpg images/image3.jpg
Makefile:16: Multiple sources for images/image2.jpg, generating from images/image2.png
images/image2.png -> images/image2.jpg
gm mogrify -background white -colorspace CMYK -density 1200 -format jpg images/image2.png
gm mogrify: Improper image header (images/image2.png).
Makefile:16: recipe for target 'images/image2.jpg' failed
make: *** [images/image2.jpg] Error 1

Convert any image format to JPG

Get the memorystream and then use System.Drawing

var stream = new MemoryStream(byteArray)
Image img = new Bitmap(stream);
img.Save(@"c:\s\pic.png", System.Drawing.Imaging.ImageFormat.Png);

The last line there where you save the file, you can select the format.

PHP - convert all images to jpg using Imagick - bad quality

The image is not in "bad quality" (there is no blurry areas found), but the difference between 2 images is caused by transparent PNG to JPG conversion.

Before you crop the image, add these two lines:

// set background to white (Imagick doesn't know how to deal with transparent background if you don't instruct it)
$img->setImageBackgroundColor(new ImagickPixel('white'));

// flattens multiple layers
$img = $img->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);

Converting all files (.jpg to .png) from a directory in Python

You can convert the opened image as RGB and then you can save it in any format.
You can try the following code :

from PIL import Image
import os

directory = r'D:\PATH'
c=1
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
name='img'+str(c)+'.png'
rgb_im = im.convert('RGB')
rgb_im.save(name)
c+=1
print(os.path.join(directory, filename))
continue
else:
continue

How to convert all PNGs in a folder to JPG in order to make a video?

Disclaimer: Here is a solution to the questions that you asked that works. I've tested it. However, it's not ideal and I don't recommend it, because this code is dependent on how fast your system is able to perform asynchronous context switching.

  1. This code works on JPG, PNG, and a few other formats. I'm not sure why you needed to convert all your JPG files to PNG.
  2. The reason why your code only showed the last image in the folder is because you were running all your code synchronously on the UI thread, so it wasn't able to update the UI until your entire "for" loop was done. You need to break up the UI thread by using the async/await pattern. Look it up if you're not familiar with this way of coding.

The code:

using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;

namespace _69201085
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

public void UpdateImage(string imageName)
{
ImportImage.Source = new BitmapImage(new Uri(imageName));
}

private async Task ShowFilesInFolder(string workingDirectory)
{
var textFile = Path.Combine(workingDirectory, "files.txt");
if (File.Exists(textFile))
{
// Parse the file, then iterate through all of the listed images at 25 FPS
var lines = await File.ReadAllLinesAsync(textFile);
foreach (var line in lines)
{
var imageName = Path.Combine(workingDirectory, line.Trim());
// Check that the file exists before you try to change the image
if (File.Exists(imageName))
{
// Make sure that the file is one of the approved image formats
if (
Path.GetExtension(imageName).ToLower() == ".jpg" ||
Path.GetExtension(imageName).ToLower() == ".png" ||
Path.GetExtension(imageName).ToLower() == ".jpeg" ||
Path.GetExtension(imageName).ToLower() == ".jfif" ||
Path.GetExtension(imageName).ToLower() == ".gif" ||
Path.GetExtension(imageName).ToLower() == ".bmp"
)
{
// Update the image
UpdateImage(imageName);

// If you want 25 FPS, then wait 40 ms
await Task.Delay(40);
}
}
}
}
}

private async void Window_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

string folder = Path.GetFullPath(files[0]);
if (!Directory.Exists(folder))
{
folder = Path.GetDirectoryName(files[0]);
}

// Verify that the directory/folder exists
if (Directory.Exists(folder))
{
await ShowFilesInFolder(folder);
}
}
}
}
}

And the xaml:

<Window x:Class="_69201085.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Drop="Window_Drop" AllowDrop="True">
<Grid>
<StackPanel x:Name="FileDropStackPanel">
<Image x:Name="ImportImage" Stretch="Fill" />
</StackPanel>
</Grid>
</Window>

Lastly, the code assumes your "files.txt" is listed without the directory name, only the file names. Like this:

file1.jpg
file2.PNG
file3.bmp
file4.jpg
...

how to convert a directory of image on png to jpg in python

Use pathlib for the filesystem access. That is more pythonic way to do.

from pathlib import Path
from PIL import Image

inputPath = Path("E:/pre/png")
inputFiles = inputPath.glob("**/*.png")
outputPath = Path("E:/pre/jpeg")
for f in inputFiles:
outputFile = outputPath / Path(f.stem + ".jpg")
im = Image.open(f)
im.save(outputFile)


Related Topics



Leave a reply



Submit