-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathsvg-render.html
300 lines (273 loc) · 10.7 KB
/
svg-render.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG to JPEG/PNG</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-size: 16px;
}
textarea, input, button, select {
font-size: 16px;
}
#dropZone {
width: 100%;
height: 150px;
border: 2px dashed #ccc;
border-radius: 5px;
padding: 10px;
margin: 10px 0;
position: relative;
box-sizing: border-box;
}
#dropZone.dragover {
border-color: #000;
background-color: #f0f0f0;
}
#svgInput {
width: 100%;
height: 100%;
border: none;
resize: none;
box-sizing: border-box;
}
#imageContainer {
margin-top: 20px;
text-align: center;
}
#convertedImage {
max-width: 90%;
cursor: pointer;
transition: max-width 0.3s ease;
}
#convertedImage.full-size {
max-width: unset;
}
#base64Output {
word-break: break-all;
white-space: pre-wrap;
}
.option-group {
margin-bottom: 10px;
}
#fileInput {
margin-bottom: 10px;
}
#downloadLink, #loadExampleLink {
display: inline-block;
margin-top: 10px;
margin-right: 10px;
}
#widthInput {
width: 60px;
}
#bgColor {
vertical-align: middle;
}
#fileSize {
margin-left: 10px;
}
</style>
</head>
<body>
<h1>SVG to JPEG/PNG</h1>
<input type="file" id="fileInput" accept=".svg">
<a href="https://gist.githubusercontent.com/simonw/aedecb93564af13ac1596810d40cac3c/raw/83e7f3be5b65bba61124684700fa7925d37c36c3/tiger.svg" id="loadExampleLink">Load example image</a>
<div id="dropZone">
<textarea id="svgInput" placeholder="Paste your SVG code here or drag & drop an SVG file"></textarea>
</div>
<div class="option-group">
<label>
<input type="radio" name="format" value="image/jpeg" checked> JPEG
</label>
<label>
<input id="pngRadio" type="radio" name="format" value="image/png"> PNG
</label>
</div>
<div class="option-group">
<label for="bgColor">Background Color:</label>
<input type="color" id="bgColor" value="#ffffff">
<label>
<input type="checkbox" id="transparentBg"> Transparent
</label>
</div>
<div class="option-group">
<label for="widthInput">Output Width:</label>
<input type="number" id="widthInput" value="800" min="1">
</div>
<button onclick="convertSvgToImage()">Convert SVG</button>
<div id="imageContainer"></div>
<a id="downloadLink" style="display: none;">Download Image</a>
<span id="fileSize"></span>
<div id="output" style="display: none;">
<h2>Base64 Image Tag:</h2>
<button id="copyImageButton" onclick="copyBase64Tag()">Copy image tag</button>
<pre id="base64Output"></pre>
</div>
<script>
const dropZone = document.getElementById('dropZone');
const svgInput = document.getElementById('svgInput');
const fileInput = document.getElementById('fileInput');
const widthInput = document.getElementById('widthInput');
const loadExampleLink = document.getElementById('loadExampleLink');
const bgColor = document.getElementById('bgColor');
const transparentBg = document.getElementById('transparentBg');
const fileSizeSpan = document.getElementById('fileSize');
const outputDiv = document.getElementById('output');
const copyImageButton = document.getElementById('copyImageButton');
// Load example image functionality
loadExampleLink.addEventListener('click', (e) => {
e.preventDefault();
const exampleSvgUrl = loadExampleLink.href;
fetch(exampleSvgUrl)
.then(response => response.text())
.then(data => {
svgInput.value = data;
})
.catch(error => {
console.error('Error loading example SVG:', error);
alert('Failed to load example SVG. Please try again later.');
});
});
// Color and transparency handling
bgColor.addEventListener('input', () => {
transparentBg.checked = false;
});
transparentBg.addEventListener('change', () => {
if (transparentBg.checked) {
bgColor.value = "#ffffff";
pngRadio.click();
}
});
// Drag and drop functionality
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('dragover');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('dragover');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('dragover');
const file = e.dataTransfer.files[0];
if (file && file.type === 'image/svg+xml') {
readFile(file);
}
});
// File input functionality
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file && file.type === 'image/svg+xml') {
readFile(file);
}
});
function readFile(file) {
const reader = new FileReader();
reader.onload = (e) => {
svgInput.value = e.target.result;
};
reader.readAsText(file);
}
function convertSvgToImage() {
let svgInput = document.getElementById('svgInput').value;
const imageContainer = document.getElementById('imageContainer');
const base64Output = document.getElementById('base64Output');
const downloadLink = document.getElementById('downloadLink');
const format = document.querySelector('input[name="format"]:checked').value;
const newWidth = parseInt(widthInput.value) || 800;
// Clear previous content
imageContainer.innerHTML = '';
base64Output.textContent = '';
downloadLink.style.display = 'none';
fileSizeSpan.textContent = '';
// Find the <?xml tag and ignore everything before it
const xmlIndex = svgInput.indexOf('<?xml');
if (xmlIndex !== -1) {
svgInput = svgInput.substring(xmlIndex);
}
// Create a temporary SVG element
const svgElement = new DOMParser().parseFromString(svgInput, 'image/svg+xml').documentElement;
if (!svgElement || svgElement.nodeName !== 'svg') {
alert('Invalid SVG input');
return;
}
// Get SVG viewBox
let viewBox = svgElement.getAttribute('viewBox');
let width, height;
if (viewBox) {
[, , width, height] = viewBox.split(' ').map(Number);
} else {
width = parseInt(svgElement.getAttribute('width')) || 300;
height = parseInt(svgElement.getAttribute('height')) || 150;
}
// Calculate new dimensions
const aspectRatio = width / height;
const newHeight = Math.round(newWidth / aspectRatio);
// Create off-screen canvas
const canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight;
// Draw SVG on canvas
const ctx = canvas.getContext('2d');
// Set background color if not transparent
if (!transparentBg.checked) {
ctx.fillStyle = bgColor.value;
ctx.fillRect(0, 0, newWidth, newHeight);
}
const svgBlob = new Blob([svgInput], {type: 'image/svg+xml;charset=utf-8'});
const URL = window.URL || window.webkitURL || window;
const svgUrl = URL.createObjectURL(svgBlob);
const img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, newWidth, newHeight);
URL.revokeObjectURL(svgUrl);
// Convert to selected format
const imageDataUrl = canvas.toDataURL(format);
// Calculate file size
const fileSizeInBytes = Math.round((imageDataUrl.length * 3) / 4);
const fileSizeInKB = (fileSizeInBytes / 1024).toFixed(2);
// Display converted image
const convertedImg = document.createElement('img');
convertedImg.src = imageDataUrl;
convertedImg.id = 'convertedImage';
convertedImg.onclick = toggleImageSize;
imageContainer.appendChild(convertedImg);
// Set up download link and display file size
downloadLink.href = imageDataUrl;
downloadLink.download = `converted_image.${format === 'image/jpeg' ? 'jpg' : 'png'}`;
downloadLink.style.display = 'inline-block';
fileSizeSpan.textContent = `(${fileSizeInKB} KB)`;
// Display base64 image tag
const imgTag = `<img src="${imageDataUrl}" alt="Converted ${format === 'image/jpeg' ? 'JPEG' : 'PNG'}" width="${newWidth}" height="${newHeight}">`;
base64Output.textContent = imgTag;
outputDiv.style.display = 'block';
};
img.src = svgUrl;
}
function toggleImageSize() {
const img = document.getElementById('convertedImage');
img.classList.toggle('full-size');
}
function copyBase64Tag() {
const base64Output = document.getElementById('base64Output');
const range = document.createRange();
range.selectNode(base64Output);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
const origText = copyImageButton.innerText;
copyImageButton.innerText = 'Copied to clipboard';
setTimeout(() => {
copyImageButton.innerText = origText;
}, 2000);
}
</script>
</body>
</html>