Image Converter script for PNG to JPG & JPG to PNG

Page 1

script for PNG to JPG & JPG to PNG

Image Converter
Table of Contents ● Introduction ● File Structure ● UI of Image Converter ● The logic behind PNG to JPG Image converter ● Convert Image Format ● Download image ● Conclusion Introduction With the upcoming Halloween festive season in mind, we are bringing coding tutorials in which we will convert image formats: PNG to JPG, JPG to PNG, and other image formats such as GIFs to PNG, GIFs to JPG, or even JPEG to PNG or JPEG to GIFs, etc. We power our image converter script with PHP Because it provides built in modules that will allow us to achieve maximum results with minimum coding effort. And as always, we are going to code this project in VS Code editor Wanna know why? Check this post out

So without further talks, let’s jump into code But before that check this demo out to know what our final project looks like:

Demo of Image converter

File Structure

Since this project contains multiple files we will define a folder and file structure as well As usual, we will give you complete details So the file will be as mentioned in the below picture:

UI of Image Converter

Now that we are aware of all files we need to make, let’s start with the main file “index.php“ And furthermore, we will divide our code for simplicity:

● “header.php“: this file contains only the basic details of the navigation bar of our JPG to PNG image converter And we will include this file in our “index php“ With a separate header file, we don’t need to code navigation related changes to all files. One of the benefits of using a backend language like PHP

● “footer.php“: Like the header file, our footer content is separated into another file called “footerphp” For now, we only writing basic code And loading our vital javascript file for Bootstrap 5.

● “social _link.php“: this file is purely for enabling those awesome looking social icons that you see on all modern websites

Now let’s see the UI/UX code of our PNG to JPG converter “headerphp“

Folder and File Structure PNG to JPG Image Converter

<!DOCTYPE html>

<html lang="en"> <head>

<meta charset="UTF 8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device width, initial scale=1.0"> <title>Image Converter | JPG to PNG | JPG to GIF | PNG to JPG | PNG to GIF | GIF to JPG | GIF to PNG | JPEG to PNG | JPEG to GIF</title>

<meta name="title" content="Image Converter">

<meta name="description" content="Ads Free Image Converter that allows you to convert any image to JPG, PNG, and GIF You can convert these and vice versa too We promise zero ads ">

<meta name="keywords" content="Image Converter, JPG Converter, PNG Converter, GIF Converter, JPG to PNG, JPG to GIF, PNG to JPG, PNG to GIF, GIF to JPG, GIF to PNG, JPEG to PNG, JPEG to GIF">

<meta name="robots" content="index, follow">

<meta http equiv="Content Type" content="text/html; charset=utf 8">

<meta name="language" content="English">

<meta name="revisit after" content="7 days">

<meta name="author" content="Pawan">

<! Favicon >

<link rel="apple touch icon" sizes="180x180" href="img/apple touch icon png"> <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32 png"> <link rel="icon" type="image/png" sizes="16x16" href="img/favicon 16x16.png">

<! Links > <link href="https://cdn jsdelivrnet/npm/bootstrap@5 2 0/dist/css/bootstrap min css" rel="stylesheet"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts gstatic com" crossorigin> <link href="https://fonts googleapis com/css2?family=Quicksand&display=swap" rel="stylesheet"> <link rel="stylesheet" href="css/style.css">

class="d-flex

class="navbar

min-vh-100">

</head> <body
flex-column
<nav
navbar expand lg bg light only top navbar"> <div class="container fluid"> <a class="navbar brand" href="index php"><img src="img/logo png" alt="Image Converter Logo"></a> </div> </nav> <br> Now our main file that first in our browser Do note down that all our file link back to our main file “index.php“ <?php

//import the converter class require('image converter.php'); if ($ FILES) { $obj = new Image converter(); //call upload function and send the $ FILES, target folder and input name $upload = $obj >upload image($ FILES, 'uploads', 'fileToUpload'); if ($upload) { $imageName = urlencode($upload[0]); $imageType = urlencode($upload[1]); if ($imageType == 'jpeg') { $imageType = 'jpg'; } header('Location: convert.php?imageName=' . $imageName . '&imageType=' . $imageType); } } ?> <?php include("includes/header.php"); ?> <div class="container pb 4"> <div class="row"> <div class="col col-lg-12 col-md-12 col-sm-12"> <h1 class="text center h2 fw bold">Image Converter</h1> <h2 class="text center h4">ConvertAny image to JPG, PNG, GIF</h2> <br> <div class="card text center mx auto p 2 gradient card"> <div class="card body"> <h4 class="card title h4 fw bold">Upload and Convert Image of your choice</h4> <p class="card-text">JPG to PNG | JPG to GIF | PNG to JPG | PNG to GIF | GIF to JPG | GIF to PNG | JPEG to PNG | JPEG to GIF</p> </div> <div class="card body"> <form action="" enctype="multipart/form data" method="post" onsubmit="return checkEmpty()"> <div class="mb 3"> <label for="fileToUpload" class="form-label">Upload file</label> <input type="file" class="form control" name="fileToUpload" id="fileToUpload"> </div> <button type="submit" class="btn btn warning btn lg fw bold"><i class="fa solid fa-upload"></i> Upload</button> </form> </div> </div> </div> </div> <?php include once("includes/social link php"); ?> </div> <?php include("includes/footer.php"); ?>

Note: Here are some important points to keep in mind when to convert png to jpg or vice versa.

● “image_converter.php“: this is an important file for our project Hence we have made it require Unlike “headerphp” or “social link php” Why? Read this article about the difference between require() and include function.

● In our image uploading form code, we added “enctype=”multipart/form data“ This is a compulsory HTMLattribute if you want to upload a file in your HTMLform Read more about the Enctype attribute in this MDN guide

Lastly,

class="bg dark mt auto"> <div class="container

<p class="text light text center py 3">@2022 Image Converter ||All Right Reserved || <a href="https://beproblemsolvercom">Designed by Be Problem Solver</a></p> </div> </footer> </body> <! JavaScript Bundle

> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script> <script src="https://kit.fontawesome.com/0a82b36f45.js" crossorigin="anonymous"></script> <script src="js/main js"></script> </html>

we need to code our footer: “footer.php“ <footer
fluid">
with Popper
As you saw, we relied on Bootstrap 5 for major CSS changes But still, need a tiny bit of custom CSS to make our JPG to PNG converter shine “style.css“ /*Author: Pawan */ /* Custom Styles Here */ :root { theme color primary: #C197D2; } /* Utility */ body { background image: url( /img/bg jpg); background-image: url( /img/bg svg); background size: cover; font size: 16px; position: relative; font-family: 'Quicksand', sans-serif; } /* Social Icons */ fa-square-facebook {

color: #3b5998; }

.fa square twitter { color: #00acee; }

.fa square instagram { color: #f09433; }

social icons btn:hover { border color: transparent; } /* Navbar */ .only top navbar { background color: var( theme color primary) !important; } /* Card */ .gradient card { background: linear gradient(90deg, #C197D2 0%, #f8a8c5 100%); } /* Select Element */ .select box select { width: 60%; margin: 0 auto; } img 200 { height: 200px; }

We are done with the UI part Don’t

download images used in this project at our Github Repo Or feel free to use your images for styling

Now let’s

JPG

converter work.

Check our post! The logic behind PNG to JPG Image converter

For ease

or in an

worry you can
see what we code into other files to make our
to PNG image
But before that wanna learn how to useAPIs in your web project
app?
of use and to separate UI from logic we have created the “image converterphp” file.This file is contains our PHPmodules which convert jpg to png or convert png to jpg. <?php class Image converter{ function convert image($convert type, $target dir, $image name, $image quality=100){ $target dir = "$target dir/"; $image = $target dir$image name; $img name = $this >remove extension from image($image);

if($convert type == 'png'){

$binary = imagecreatefromstring(file get contents($image)); $image quality = floor(10 ($image quality / 10)); ImagePNG($binary, $target dir$img name ' ' $convert type, $image quality); return $img name ' ' $convert type;

}

if($convert type == 'jpg'){

$binary = imagecreatefromstring(file get contents($image)); imageJpeg($binary, $target dir$img name ' ' $convert type, $image quality); return $img name.'.'.$convert type;

}

if($convert type == 'gif'){

$binary = imagecreatefromstring(file get contents($image)); imageGif($binary, $target dir$img name ' ' $convert type, $image quality); return $img name ' ' $convert type; } return false; } public function upload image($files, $target dir, $input name){ $target dir = "$target dir/"; $base name = basename($files[$input name]["name"]); $imageFileType = $this >get image type($base name); $new name = $this->get dynamic name($base name, $imageFileType); $target file = $target dir . $new name; $validate = $this >validate image($files[$input name]["tmp name"]); if(!$validate){

echo "Doesn't seem like an image file :("; return false; }

$file size = $this >check file size($files[$input name]["size"], 1000000); if(!$file size){ echo "You cannot upload more than 1MB file"; return false;

}

$file type = $this >check only allowed image types($imageFileType); if(!$file type){

echo "You cannot upload other than JPG, JPEG, GIF and PNG"; return false;

}

if (move uploaded file($files[$input name]["tmp name"], $target file)) { return array($new name, $imageFileType); } else { echo "Sorry, there was an error uploading your file "; } } protected function get image type($target file){ $imageFileType = pathinfo($target file,PATHINFO EXTENSION); return $imageFileType;

protected function validate image($file){ $check = getimagesize($file); if($check !== false) { return true; } return false; } protected function check file size($file, $size limit){ if ($file > $size limit) { return false; } return true; } protected function check only allowed image types($imagetype){ if($imagetype != "jpg" && $imagetype != "png" && $imagetype != "jpeg" && $imagetype != "gif" ) { return false; } return true; } protected function get dynamic name($basename, $imagetype){ $only name = basename($basename, ' ' $imagetype); $combine time = $only name.' '.time(); $new name = $combine time ' ' $imagetype; return $new name; } protected function remove extension from image($image){ $extension = $this >get image type($image); $only name = basename($image, ' ' $extension); return $only name;

Image Format

}
} } ?> Convert
Now that we understood the logic let’s keep coding to the part where we convert our image format. Or convert png to jpg and convert jpg to png. We can even convert any image format to GIF as well. “convert php“ <?php require('image converterphp'); $imageType = '';

$download = false; if ($ GET) { $imageType = urldecode($ GET['imageType']); $imageName = urldecode($ GET['imageName']); } else { header('Location:index.php'); }

if ($ POST) { $convert type = $ POST['convert type']; $obj = new Image converter(); $target dir = 'uploads'; $image = $obj >convert image($convert type, $target dir, $imageName); if ($image) { $download = true; } }

$types = array( 'png' => 'PNG', 'jpg' => 'JPG', 'gif' => 'GIF', ); ?> <?php include("includes/headerphp"); ?> <div class="container pb 4"> <div class="row"> <div class="col col lg 12 col md 12 col sm 12"> <h2 class="text-center lh-lg fw-bold">Image Converter</h2> <h4 class="text center lh lg">ConvertAny image to JPG, PNG, GIF</h4> <p class="text center card text">JPG to PNG | JPG to GIF | PNG to JPG | PNG to GIF | GIF to JPG | GIF to PNG | JPEG to PNG | JPEG to GIF</p> <div class="card text center mx auto p 2 gradient card"> <div class="card body"> <?php if (!$download) { ?> <form method="post" action=""> <h5 class="py 2 h4 fw bold">File Uploaded, Select below option to convert!</h5> <img src="uploads/<?= $imageName; ?>" class="img fluid rounded img 200 mb 4"> <div class="w 50 mb 3 mx auto"> <label class="form-label h5 fw-bold">ConvertTo:</label> <select name="convert type" class="form control"> <?php foreach ($types as $key => $type) { ?> <?php if ($key != $imageType) { ?> <option value="<?= $key; ?>"><?= $type; ?></option> <?php } ?> <?php } ?> </select> </div> <div class="mb 3">

<button type="submit" class="btn btn success btn lg fw bold"><i class="fa solid fa arrows rotate"></i> Convert</button> </div> </form> <?php } ?> <?php if ($download) { ?> <h5 class="py 2 h4 fw bold"> Converted to <?php echo ucwords($convert type); ?></h5> <img src="<?= $target dir '/' $image; ?>" class="img fluid rounded img 200 mb 4" /> <div class="mb-3"> <a href="download.php?filepath=<?php echo $target dir . '/' . $image; ?>" class="btn btn success btn lg mb 2"><i class="fa solid fa download"></i> Download Converted Image</a>

<a href="index.php" class="btn btn primary"><i class="fa solid fa square arrow up right mb 2"></i> ConvertAnother</a> </div> <?php } ?> </div> </div> </div> </div> <?php include once("includes/social link.php"); ?> </div> <?php include("includes/footerphp"); ?>

Here is how our image is previewed in image converter:

Preview of uploaded image into our image converter Download image

Almost to the finish line! Now we only to create a file that will allow us to download our converted file.

download.php“

<?php

$file path = $ GET['filepath'];

header('Content Type: application/octet stream'); header("Content-Transfer-Encoding: Binary"); header("Content disposition: attachment; filename=\"" . basename($file path) . "\""); readfile($file path); ?>

Congrats! Now you completely built your own image converter that can convert png to jpg. Or if you desire then convert jpg to png Or maybe convert them to gifs

And finally, you can download our JPG to PNG and PNG to JPG image converter files from the below Github Link:

Download Image converter script

Conclusion

We hope you enjoyed this article about Image Converter scripts for PNG to JPG and JPG to PNG conversion! If you have any questions or concerns about our scripts or any other scripts on our website, please contact us anytime. Or leave a comment below.

Also, check out our previous post where we linked our HTMLform to Google Sheets for collecting data. Or read on how to submit a form without any page refresh.

Thank you for reading, we are always excited when one of our posts is able to provide useful information on a topic like this! Keep Reading and coding!Ta-Da!

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.