Friday, 14 July 2023

jpg to PNG

In the JavaScript code, we attach an event listener to the "Convert to PNG" button, which triggers the convertToPNG function. This function checks if a JPG file is selected, reads the file using the FileReader API, and creates an img element to load the JPG image. Once the image is loaded, a canvas element is created and the image is drawn onto it. Finally, the canvas data is converted to a PNG data URL, and the result is displayed in the result-container div.

Make sure to save the HTML file as index.html, the CSS file as styles.css, and the JavaScript file as script.js. Place all three files in the same directory, and you should be able to run the JPG to PNG Converter tool in a web browser
<!DOCTYPE html>
<html>
<head>
  <title>JPG to PNG Converter</title>
  <link rel="stylesheet" type="text/css" href=".container {
  text-align: center;
  margin-top: 100px;
}

h1 {
  color: #1e90ff;
}

.input-container {
  margin: 20px 0;
}

input[type="file"] {
  display: none;
}

label {
  background-color: #1e90ff;
  color: white;
  padding: 10px 20px;
  cursor: pointer;
}

button {
  background-color: #1e90ff;
  color: white;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
}

#result-container {
  margin-top: 20px;
}
">
</head>
<body>
  <div class="container">
    <h1>JPG to PNG Converter</h1>
    <div class="input-container">
      <input type="file" id="file-input">
      <label for="file-input">Choose a JPG file</label>
    </div>
    <button id="convert-btn">Convert to PNG</button>
    <div id="result-container"></div>
  </div>

  <script src="document.getElementById('convert-btn').addEventListener('click', convertToPNG);

function convertToPNG() {
  var fileInput = document.getElementById('file-input');
  var file = fileInput.files[0];

  if (!file || file.type !== 'image/jpeg') {
    alert('Please select a JPG image file.');
    return;
  }

  var reader = new FileReader();

  reader.onload = function(e) {
    var img = document.createElement('img');
    img.src = e.target.result;

    img.onload = function() {
      var canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;

      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);

      var pngData = canvas.toDataURL('image/png');

      var resultContainer = document.getElementById('result-container');
      resultContainer.innerHTML = '<h2>Converted Image:</h2><img src="' + pngData + '">';
    };
  };

  reader.readAsDataURL(file);
}
"></script>
</body>
</html>

No comments:

Post a Comment

configuration of website

Menu Type: Dropdown with Full Width Ensure the navigation items in the dropdown menu contain relevant keywords related to the we...