Header Ads

JPG to PNG converter

JPG to PNG Converter

JPG to PNG Converter


Download PNG file



The code below creates a simple HTML form with a file input for selecting a JPG file, and a "Convert" button that triggers the conversion process using JavaScript. The convert() function uses the HTML5 FileReader API to read the selected JPG file and convert it to a PNG data URL, which is then displayed in a preview div using a dynamically created Image object. The CSS styles make the page responsive and mobile-friendly. Note that this code only works in modern web browsers that support the required HTML5 and JavaScript APIs.

HTML CODE : 



  <head>
    <title>JPG to PNG Converter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      /* Add some basic styling */
      body {
        font-family: Arial, sans-serif;
        text-align: center;
        padding: 20px;
      }
      h1 {
        margin-top: 0;
      }
      input[type="file"] {
        margin-top: 20px;
      }
      #preview {
        max-width: 100%;
        height: auto;
        margin-top: 20px;
      }
    </style>
  </head>
  <body>
    <h1>JPG to PNG Converter</h1>
    <form>
      <label for="jpgFile">Choose a JPG file:</label>
      <input type="file" id="jpgFile" accept=".jpg, .jpeg">
      <br>
      <button type="button" onclick="convert()">Convert</button>
    </form>
    <div id="preview"></div>
    <script src="converter.js"></script>
  </body>


JavaScript (in converter.js): 


function convert() {
  // Get the JPG file input element and its value
  var jpgInput = document.getElementById('jpgFile');
  var jpgFile = jpgInput.files[0];

  // Create a new FileReader object
  var reader = new FileReader();

  // When the FileReader object loads the file
  reader.onload = function() {
    // Create a new Image object and set its source to the data URL
    var img = new Image();
    img.src = reader.result;

    // When the Image object is loaded
    img.onload = function() {
      // Create a new canvas element and set its dimensions to the image dimensions
      var canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;

      // Draw the image onto the canvas
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);

      // Convert the canvas to a data URL in PNG format
      var dataURL = canvas.toDataURL('image/png');

      // Create a new Image object and set its source to the data URL
      var pngImg = new Image();
      pngImg.src = dataURL;

      // Display the PNG image in the preview div
      var preview = document.getElementById('preview');
      preview.innerHTML = '';
      preview.appendChild(pngImg);
    };
  };

  // Read the JPG file as a data URL
  reader.readAsDataURL(jpgFile);
}

No comments

Powered by Blogger.