You can edit the below JavaScript code to customize the image tool.
async function processImage(originalImg, mimeType = 'image/png', quality = 0.92) {
// Helper function to create consistently styled error messages
const createErrorElement = (message) => {
const errorElement = document.createElement('div');
errorElement.textContent = message;
errorElement.style.color = 'red';
errorElement.style.padding = '10px';
errorElement.style.border = '1px solid #cc0000';
errorElement.style.backgroundColor = '#ffeeee';
errorElement.style.fontFamily = 'sans-serif';
errorElement.style.borderRadius = '4px';
return errorElement;
};
// Validate the input image object
if (!originalImg || typeof originalImg.complete !== 'boolean') {
console.error('Invalid Image object provided.');
return createErrorElement('Error: Invalid image object. Please ensure you are passing a JavaScript Image object.');
}
if (!originalImg.complete) {
// Wait for the image to load if it's not complete yet.
// This is a common pattern if the Image object was just created and src set.
// However, the prompt implies originalImg is an already processed Image object parameter.
// If it's truly not loaded, this function (as implemented) would try to draw an empty image.
// For robustness, we can add a check and wait, or return an error.
// Based on the prompt, we assume it should be loaded.
// If not, naturalWidth/Height might be 0.
console.warn('Image is not complete. Dimensions might be 0.');
// One could add a promise wrapper here to wait for onload, but that changes function signature to always async
// or requires a callback, which is not in the spec.
// For now, rely on naturalWidth/Height check.
}
if (originalImg.naturalWidth === 0 || originalImg.naturalHeight === 0) {
console.error('Image is not loaded, is invalid, or has zero dimensions.');
return createErrorElement('Error: Image is not loaded, is invalid, or has zero dimensions. Please provide a valid, loaded image.');
}
// Create a canvas element
const canvas = document.createElement('canvas');
canvas.width = originalImg.naturalWidth;
canvas.height = originalImg.naturalHeight;
// Get the 2D rendering context
const ctx = canvas.getContext('2d');
// Draw the image onto the canvas
try {
ctx.drawImage(originalImg, 0, 0, originalImg.naturalWidth, originalImg.naturalHeight);
} catch (drawError) {
console.error('Error drawing image onto canvas:', drawError);
return createErrorElement(`Error drawing image onto canvas: ${drawError.message}. The image file might be corrupted or in an unsupported format.`);
}
let dataURI;
try {
// Ensure quality is a number between 0.0 and 1.0 for relevant types
const numericQuality = Math.max(0, Math.min(1, Number(quality)));
if (mimeType === 'image/jpeg' || mimeType === 'image/webp') {
dataURI = canvas.toDataURL(mimeType, numericQuality);
} else {
// For other types like image/png, quality parameter is ignored by browsers.
// If mimeType is not supported by the browser, it will default to image/png.
dataURI = canvas.toDataURL(mimeType);
}
} catch (error) {
console.error('Error converting image to Data URI:', error);
let errorMessage = `Error converting image to Data URI: ${error.message}.`;
if (error.name === 'SecurityError') {
errorMessage += ' This may be due to cross-origin restrictions if the image source is from another domain without CORS headers enabled.';
} else {
errorMessage += ` This might be due to an unsupported MIME type ('${mimeType}') or an issue with the image data.`;
}
return createErrorElement(errorMessage);
}
// Check for empty or minimal Data URI, which might indicate an encoding failure
if (!dataURI || dataURI === 'data:,') {
console.error('Generated Data URI is empty. This can happen for very large images or if the browser failed to encode the image.');
return createErrorElement('Error: Generated Data URI is empty. The image might be too large for the browser to handle, the format unsupported, or another encoding error occurred.');
}
// Create a container element for the output
const container = document.createElement('div');
container.style.fontFamily = 'Arial, sans-serif';
container.style.padding = '10px';
container.style.border = '1px solid #ddd';
container.style.borderRadius = '4px';
container.style.backgroundColor = '#f9f9f9';
const introText = document.createElement('p');
introText.textContent = 'Image converted to Data URI successfully:';
introText.style.marginBottom = '8px';
container.appendChild(introText);
const outputTextArea = document.createElement('textarea');
outputTextArea.value = dataURI;
outputTextArea.style.width = 'calc(100% - 16px)'; // Full width accounting for padding
outputTextArea.style.minHeight = '100px';
outputTextArea.style.maxHeight = '250px';
outputTextArea.style.resize = 'vertical';
outputTextArea.style.wordBreak = 'break-all'; // Essential for long Data URIs
outputTextArea.style.fontSize = '0.9em';
outputTextArea.style.padding = '8px';
outputTextArea.style.border = '1px solid #ccc';
outputTextArea.style.borderRadius = '3px';
outputTextArea.style.fontFamily = 'monospace, Consolas, "Courier New", Courier';
outputTextArea.readOnly = true;
outputTextArea.setAttribute('aria-label', 'Image Data URI');
// Select text on focus for easy copying
outputTextArea.addEventListener('focus', function(event) {
event.target.select();
});
container.appendChild(outputTextArea);
const controlsDiv = document.createElement('div');
controlsDiv.style.marginTop = '10px';
controlsDiv.style.display = 'flex';
controlsDiv.style.alignItems = 'center';
const copyButton = document.createElement('button');
copyButton.textContent = 'Copy Data URI';
copyButton.style.padding = '8px 15px';
copyButton.style.border = '1px solid #007bff';
copyButton.style.backgroundColor = '#007bff';
copyButton.style.color = 'white';
copyButton.style.borderRadius = '3px';
copyButton.style.cursor = 'pointer';
copyButton.style.fontSize = '0.9em';
copyButton.title = 'Copy the Data URI to clipboard';
copyButton.addEventListener('mouseenter', () => { copyButton.style.backgroundColor = '#0056b3'; });
copyButton.addEventListener('mouseleave', () => { copyButton.style.backgroundColor = '#007bff'; });
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
copyButton.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(dataURI);
copyButton.textContent = 'Copied!';
copyButton.disabled = true;
copyButton.style.backgroundColor = '#28a745'; // Green for success
copyButton.style.borderColor = '#28a745';
setTimeout(() => {
copyButton.textContent = 'Copy Data URI';
copyButton.disabled = false;
copyButton.style.backgroundColor = '#007bff';
copyButton.style.borderColor = '#007bff';
}, 2000);
} catch (err) {
console.error('Failed to copy Data URI using Clipboard API: ', err);
outputTextArea.focus(); // Selects text due to focus listener
alert('Automatic copy failed. The Data URI has been selected; please press Ctrl+C (or Cmd+C) to copy manually. Error: ' + err.message);
}
});
} else {
// Fallback for older browsers or insecure contexts (e.g. HTTP)
copyButton.addEventListener('click', () => {
outputTextArea.focus(); // Selects text due to focus listener
alert('Automatic copy is not available in this browser/context. The Data URI has been selected in the text area. Please press Ctrl+C (or Cmd+C on Mac) to copy it manually.');
});
}
controlsDiv.appendChild(copyButton);
container.appendChild(controlsDiv);
// Preview of the converted image
const previewHeader = document.createElement('p');
previewHeader.textContent = 'Preview:';
previewHeader.style.marginTop = '15px';
previewHeader.style.marginBottom = '5px';
previewHeader.style.fontWeight = 'bold';
container.appendChild(previewHeader);
const previewImg = document.createElement('img');
previewImg.src = dataURI;
previewImg.alt = 'Preview of converted image';
previewImg.style.display = 'block';
previewImg.style.maxWidth = '100%';
previewImg.style.maxHeight = '200px'; // Limit display height of preview
previewImg.style.border = '1px solid #ccc';
previewImg.style.borderRadius = '3px';
previewImg.style.objectFit = 'contain'; // Ensure aspect ratio is maintained
container.appendChild(previewImg);
return container;
}
Free Image Tool Creator
Can't find the image tool you're looking for? Create one based on your own needs now!
The Image To Data URI Converter transforms images into Data URI format, enabling users to easily embed images directly into HTML or CSS files as a string. This tool is useful for web developers and designers who want to reduce HTTP requests by including image data inline, enhancing performance and simplifying file management. It supports commonly used image formats and allows users to adjust the quality of the output Data URI, making it a versatile solution for various web development projects.