PageSourceSearch

https://www.svgai.org/_next/static/chunks/7443.3172a8a73ce9b0e4.js

js svgai.org collected 2026-10-04 08:38:25 UTC 25,203 bytes, 557 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[7443],{32919:(e,t,s)=>{s.d(t,{A:()=>a});let a=(0,s(19946).A)("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]])},47443:(e,t,s)=>{s.r(t),s.d(t,{default:()=>x,frontmatter:()=>p});var a=s(95155),r=s(5674),n=s(88145),o=s(88482),i=s(49026),c=s(34964),d=s(34869),l=s(28883),m=s(54213),g=s(62332),h=s(32919);let p={title:"Base64 to SVG Converter: Decode Data URIs for API & Email Integration",description:"Convert Base64 encoded strings to SVG files instantly. Perfect for API responses, email embeds, and database storage. Handle data URIs with automatic MIME type detection.",keywords:["base64 to svg","decode base64","data uri to svg","api integration","email embedding","base64 decoder","svg extraction","data url converter"],date:"2025-08-17",author:"API Integration Team",expertise:"Backend engineers specializing in data encoding and API architecture",search_volume:480};function u(e){let t={h1:"h1",h2:"h2",h3:"h3",p:"p",strong:"strong",...(0,r.R)(),...e.components};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(t.h1,{children:"Base64 to SVG Converter: Decode & Extract Vector Graphics"}),"\n",(0,a.jsxs)("div",{className:"flex gap-2 mb-6",children:[(0,a.jsx)(n.E,{variant:"secondary",children:"480 searches/month"}),(0,a.jsx)(n.E,{variant:"outline",children:"API Ready"}),(0,a.jsx)(n.E,{variant:"outline",children:"Email Compatible"}),(0,a.jsx)(n.E,{className:"bg-gradient-to-r from-purple-500 to-blue-500 text-white",children:"Zero Dependencies"})]}),"\n",(0,a.jsx)(t.h2,{children:"Decode Base64 SVGs for Modern Web Applications"}),"\n",(0,a.jsxs)(t.p,{children:["Our Base64 to SVG converter, built by API architecture specialists, instantly decodes Base64 strings and data URIs to clean SVG files. Essential for processing ",(0,a.jsx)(t.strong,{children:"API responses"}),", ",(0,a.jsx)(t.strong,{children:"email attachments"}),", and ",(0,a.jsx)(t.strong,{children:"database-stored graphics"})," with automatic MIME type detection and validation."]}),"\n",(0,a.jsx)(o.Zp,{className:"p-6 my-8 bg-gradient-to-r from-purple-50 via-blue-50 to-indigo-50",children:(0,a.jsxs)("div",{className:"grid md:grid-cols-3 gap-6",children:[(0,a.jsxs)("div",{className:"flex items-start gap-3",children:[(0,a.jsx)(d.A,{className:"h-6 w-6 text-purple-600 mt-1"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("h3",{className:"font-bold mb-2",children:"API Integration"}),(0,a.jsx)("p",{className:"text-sm",children:"Process Base64 from REST/GraphQL responses instantly"})]})]}),(0,a.jsxs)("div",{className:"flex items-start gap-3",children:[(0,a.jsx)(l.A,{className:"h-6 w-6 text-blue-600 mt-1"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("h3",{className:"font-bold mb-2",children:"Email Extraction"}),(0,a.jsx)("p",{className:"text-sm",children:"Decode inline email graphics and attachments"})]})]}),(0,a.jsxs)("div",{className:"flex items-start gap-3",children:[(0,a.jsx)(m.A,{className:"h-6 w-6 text-indigo-600 mt-1"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("h3",{className:"font-bold mb-2",children:"Database Recovery"}),(0,a.jsx)("p",{className:"text-sm",children:"Extract SVGs from Base64 database columns"})]})]})]})}),"\n",(0,a.jsx)(t.h2,{children:"Understanding Base64 SVG Encoding"}),"\n",(0,a.jsx)(t.h3,{children:"What is Base64 SVG?"}),"\n",(0,a.jsx)(t.p,{children:"Base64 encoding converts SVG text into ASCII strings for safe transmission:"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`// Original SVG
2const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
3<circle cx="50" cy="50" r="40" fill="blue"/>
4</svg>';
5
6// Base64 encoded
7const base64 = 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj4KICA8Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgZmlsbD0iYmx1ZSIvPgo8L3N2Zz4=';
8
9// Data URI format
10const dataUri = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj4KICA8Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgZmlsbD0iYmx1ZSIvPgo8L3N2Zz4=';`}),"\n",(0,a.jsx)(t.h3,{children:"Common Use Cases"}),"\n",(0,a.jsxs)(i.Fc,{className:"my-6 border-blue-200 bg-blue-50",children:[(0,a.jsx)(g.A,{className:"h-4 w-4"}),(0,a.jsx)(i.TN,{children:(0,a.jsxs)(t.p,{children:[(0,a.jsx)("strong",{children:"Pro Tip:"})," While Base64 increases file size by ~33%, it eliminates HTTP requests and enables inline embedding. Use for small SVGs (< 5KB) or when reducing requests is critical."]})})]}),"\n",(0,a.jsx)(t.h2,{children:"Implementation Examples"}),"\n",(0,a.jsx)(t.h3,{children:"JavaScript/TypeScript Decoder"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`class Base64ToSVGConverter {
11// Decode plain Base64 string
12decode(base64String: string): string {
13  // Remove data URI prefix if present
14  const base64 = this.extractBase64(base64String);
15  
16  // Decode Base64 to text
17  const decoded = atob(base64);
18  
19  // Validate SVG structure
20  if (!this.isValidSVG(decoded)) {
21    throw new Error('Decoded content is not valid SVG');
22  }
23  
24  return decoded;
25}
26
27// Extract Base64 from data URI
28extractBase64(input: string): string {
29  const dataUriRegex = /^data:image/svg+xml;(base64|charset=[w-]+),(.+)$/;
30  const match = input.match(dataUriRegex);
31  
32  if (match) {
33    if (match[1] === 'base64') {
34      return match[2];
35    } else {
36      // Handle URL-encoded SVG
37      return btoa(decodeURIComponent(match[2]));
38    }
39  }
40  
41  // Assume plain Base64 if not data URI
42  return input.replace(/s/g, '');
43}
44
45// Validate SVG content
46isValidSVG(content: string): boolean {
47  try {
48    const parser = new DOMParser();
49    const doc = parser.parseFromString(content, 'image/svg+xml');
50    
51    // Check for parser errors
52    const parserError = doc.querySelector('parsererror');
53    if (parserError) {
54      console.error('SVG parsing error:', parserError.textContent);
55      return false;
56    }
57    
58    // Verify SVG root element
59    const svg = doc.documentElement;
60    return svg.nodeName.toLowerCase() === 'svg' && 
61           svg.namespaceURI === 'http://www.w3.org/2000/svg';
62  } catch (error) {
63    return false;
64  }
65}
66
67// Advanced: Handle multiple formats
68async convertFromDataSource(source: string | Blob | File): Promise<SVGResult> {
69  let base64: string;
70  
71  if (source instanceof Blob || source instanceof File) {
72    // Convert Blob/File to Base64
73    base64 = await this.blobToBase64(source);
74  } else if (typeof source === 'string') {
75    base64 = source;
76  } else {
77    throw new Error('Invalid source type');
78  }
79  
80  const svg = this.decode(base64);
81  
82  return {
83    svg,
84    metadata: this.extractMetadata(svg),
85    optimized: await this.optimize(svg),
86    download: this.createDownloadLink(svg)
87  };
88}
89
90// Extract SVG metadata
91extractMetadata(svg: string): SVGMetadata {
92  const parser = new DOMParser();
93  const doc = parser.parseFromString(svg, 'image/svg+xml');
94  const svgElement = doc.documentElement;
95  
96  return {
97    width: svgElement.getAttribute('width'),
98    height: svgElement.getAttribute('height'),
99    viewBox: svgElement.getAttribute('viewBox'),
100    title: doc.querySelector('title')?.textContent,
101    description: doc.querySelector('desc')?.textContent,
102    elementCount: doc.querySelectorAll('*').length,
103    hasAnimation: doc.querySelector('animate, animateTransform, animateMotion') !== null,
104    hasScript: doc.querySelector('script') !== null,
105    fileSize: new Blob([svg]).size
106  };
107}
108
109// Create download link
110createDownloadLink(svg: string, filename = 'decoded.svg'): string {
111  const blob = new Blob([svg], { type: 'image/svg+xml' });
112  const url = URL.createObjectURL(blob);
113  
114  // Auto-revoke after 1 minute
115  setTimeout(() => URL.revokeObjectURL(url), 60000);
116  
117  return url;
118}
119}`}),"\n",(0,a.jsx)(t.h3,{children:"Node.js/Express API Implementation"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`// API endpoint for Base64 to SVG conversion
120import express from 'express';
121import { Buffer } from 'buffer';
122import { JSDOM } from 'jsdom';
123import sanitizeHtml from 'sanitize-html';
124
125const app = express();
126app.use(express.json({ limit: '10mb' }));
127
128app.post('/api/decode/base64-to-svg', async (req, res) => {
129try {
130  const { base64, options = {} } = req.body;
131  
132  if (!base64) {
133    return res.status(400).json({ 
134      error: 'Base64 string required' 
135    });
136  }
137  
138  // Decode Base64
139  const decoded = Buffer.from(
140    base64.replace(/^data:image/svg+xml;base64,/, ''), 
141    'base64'
142  ).toString('utf-8');
143  
144  // Security: Sanitize SVG
145  const sanitized = sanitizeSVG(decoded, options.sanitize);
146  
147  // Validate SVG structure
148  const validation = validateSVG(sanitized);
149  if (!validation.valid) {
150    return res.status(400).json({ 
151      error: 'Invalid SVG content',
152      details: validation.errors 
153    });
154  }
155  
156  // Optional: Optimize SVG
157  const optimized = options.optimize ? 
158    await optimizeSVG(sanitized) : 
159    sanitized;
160  
161  res.json({
162    success: true,
163    svg: optimized,
164    metadata: extractSVGMetadata(optimized),
165    encoding: {
166      original: base64.length,
167      decoded: decoded.length,
168      optimized: optimized.length,
169      compression: ((1 - optimized.length / base64.length) * 100).toFixed(2) + '%'
170    }
171  });
172  
173} catch (error) {
174  console.error('Decoding error:', error);
175  res.status(500).json({ 
176    error: 'Failed to decode Base64 to SVG',
177    message: error.message 
178  });
179}
180});
181
182// Security sanitization
183function sanitizeSVG(svg, level = 'strict') {
184const config = {
185  strict: {
186    allowedTags: ['svg', 'g', 'path', 'circle', 'rect', 'line', 'polyline', 
187                 'polygon', 'ellipse', 'text', 'tspan', 'defs', 'clipPath', 
188                 'linearGradient', 'radialGradient', 'stop'],
189    allowedAttributes: {
190      '*': ['id', 'class', 'style', 'fill', 'stroke', 'stroke-width', 
191            'opacity', 'transform', 'd', 'points', 'x', 'y', 'cx', 'cy', 
192            'r', 'rx', 'ry', 'width', 'height', 'viewBox', 'xmlns']
193    },
194    disallowedTagsMode: 'discard'
195  },
196  moderate: {
197    // Allow more tags including filters
198    allowedTags: [...config.strict.allowedTags, 'filter', 'feGaussianBlur', 
199                 'feColorMatrix', 'feMerge', 'feMergeNode'],
200    allowedAttributes: config.strict.allowedAttributes
201  },
202  minimal: {
203    // Allow everything except scripts
204    exclusiveFilter: (frame) => {
205      return frame.tag === 'script' ? false : true;
206    }
207  }
208};
209
210return sanitizeHtml(svg, config[level] || config.strict);
211}`}),"\n",(0,a.jsx)(t.h3,{children:"Python/Flask Implementation"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`from flask import Flask, request, jsonify
212import base64
213import re
214from lxml import etree
215import json
216
217app = Flask(__name__)
218
219class Base64SVGDecoder:
220  @staticmethod
221  def decode(base64_string):
222      """Decode Base64 string to SVG"""
223      # Remove data URI prefix if present
224      base64_clean = re.sub(r'^data:image/svg+xml;base64,', '', base64_string)
225      
226      try:
227          # Decode Base64
228          decoded = base64.b64decode(base64_clean).decode('utf-8')
229          
230          # Validate SVG
231          if not Base64SVGDecoder.validate_svg(decoded):
232              raise ValueError("Invalid SVG content")
233          
234          return decoded
235      except Exception as e:
236          raise ValueError(f"Decoding failed: {str(e)}")
237  
238  @staticmethod
239  def validate_svg(svg_content):
240      """Validate SVG structure"""
241      try:
242          # Parse SVG with lxml
243          parser = etree.XMLParser(remove_blank_text=True)
244          doc = etree.fromstring(svg_content.encode(), parser)
245          
246          # Check root element
247          if doc.tag != '{http://www.w3.org/2000/svg}svg':
248              return False
249          
250          return True
251      except:
252          return False
253  
254  @staticmethod
255  def extract_metadata(svg_content):
256      """Extract SVG metadata"""
257      doc = etree.fromstring(svg_content.encode())
258      
259      return {
260          'width': doc.get('width'),
261          'height': doc.get('height'),
262          'viewBox': doc.get('viewBox'),
263          'elements': len(doc.xpath('//*')),
264          'paths': len(doc.xpath('//svg:path', namespaces={'svg': 'http://www.w3.org/2000/svg'})),
265          'file_size': len(svg_content)
266      }
267
268@app.route('/api/decode/base64-to-svg', methods=['POST'])
269def decode_base64_to_svg():
270  data = request.json
271  base64_input = data.get('base64')
272  
273  if not base64_input:
274      return jsonify({'error': 'Base64 string required'}), 400
275  
276  try:
277      decoder = Base64SVGDecoder()
278      svg = decoder.decode(base64_input)
279      metadata = decoder.extract_metadata(svg)
280      
281      return jsonify({
282          'success': True,
283          'svg': svg,
284          'metadata': metadata,
285          'size': {
286              'base64': len(base64_input),
287              'svg': len(svg),
288              'ratio': f"{(len(svg) / len(base64_input) * 100):.1f}%"
289          }
290      })
291  
292  except ValueError as e:
293      return jsonify({'error': str(e)}), 400`}),"\n",(0,a.jsx)(t.h2,{children:"API Integration Patterns"}),"\n",(0,a.jsx)(t.h3,{children:"REST API Response Handling"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`// Handle API response with embedded Base64 SVG
294async function fetchUserAvatar(userId) {
295const response = await fetch(\`/api/users/\${userId}/avatar\`);
296const data = await response.json();
297
298// API returns: { avatar: "data:image/svg+xml;base64,..." }
299if (data.avatar && data.avatar.startsWith('data:')) {
300  const converter = new Base64ToSVGConverter();
301  const svg = converter.decode(data.avatar);
302  
303  // Render SVG directly
304  document.getElementById('avatar').innerHTML = svg;
305  
306  // Or create img element
307  const img = document.createElement('img');
308  img.src = data.avatar;
309  document.body.appendChild(img);
310}
311}`}),"\n",(0,a.jsx)(t.h3,{children:"GraphQL Integration"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`# GraphQL schema with Base64 SVG
312type User {
313id: ID!
314name: String!
315avatar: String # Base64 encoded SVG
316avatarSVG: String # Decoded SVG (custom resolver)
317}
318
319# Query
320query GetUserWithAvatar($id: ID!) {
321user(id: $id) {
322  name
323  avatar # Base64
324  avatarSVG # Auto-decoded
325}
326}`}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`// GraphQL resolver
327const resolvers = {
328User: {
329  avatarSVG: (parent) => {
330    if (!parent.avatar) return null;
331    
332    // Decode Base64 to SVG
333    const base64 = parent.avatar.replace(/^data:image/svg+xml;base64,/, '');
334    return Buffer.from(base64, 'base64').toString('utf-8');
335  }
336}
337};`}),"\n",(0,a.jsx)(t.h2,{children:"Email Integration"}),"\n",(0,a.jsx)(t.h3,{children:"Extracting SVGs from Email"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`// Process email with inline Base64 SVGs
338class EmailSVGExtractor {
339extractFromHTML(emailHTML) {
340  const svgs = [];
341  
342  // Find img tags with data URIs
343  const imgRegex = /<img[^>]+src="(data:image/svg+xml;base64,[^"]+)"/g;
344  let match;
345  
346  while ((match = imgRegex.exec(emailHTML)) !== null) {
347    const dataUri = match[1];
348    const svg = this.decodeDataUri(dataUri);
349    svgs.push({
350      dataUri,
351      svg,
352      position: match.index
353    });
354  }
355  
356  // Find CSS background images
357  const cssRegex = /url((data:image/svg+xml;base64,[^)]+))/g;
358  
359  while ((match = cssRegex.exec(emailHTML)) !== null) {
360    const dataUri = match[1];
361    const svg = this.decodeDataUri(dataUri);
362    svgs.push({
363      dataUri,
364      svg,
365      position: match.index,
366      type: 'css-background'
367    });
368  }
369  
370  return svgs;
371}
372
373// Replace Base64 with actual SVG for better email client support
374optimizeForEmail(emailHTML) {
375  return emailHTML.replace(
376    /data:image/svg+xml;base64,([A-Za-z0-9+/=]+)/g,
377    (match, base64) => {
378      const svg = atob(base64);
379      // URL encode for better compatibility
380      return 'data:image/svg+xml,' + encodeURIComponent(svg);
381    }
382  );
383}
384}`}),"\n",(0,a.jsx)(t.h2,{children:"Database Storage & Retrieval"}),"\n",(0,a.jsx)(t.h3,{children:"PostgreSQL Example"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`-- Store SVGs as Base64 in database
385CREATE TABLE graphics (
386id SERIAL PRIMARY KEY,
387name VARCHAR(255),
388svg_base64 TEXT,
389svg_decoded TEXT GENERATED ALWAYS AS (
390  convert_from(decode(
391    regexp_replace(svg_base64, '^data:image/svg+xml;base64,', ''),
392    'base64'
393  ), 'UTF8')
394) STORED,
395created_at TIMESTAMP DEFAULT NOW()
396);
397
398-- Index for searching SVG content
399CREATE INDEX idx_svg_content ON graphics 
400USING gin(to_tsvector('english', svg_decoded));
401
402-- Query with automatic decoding
403SELECT 
404name,
405svg_decoded as svg,
406length(svg_base64) as base64_size,
407length(svg_decoded) as svg_size
408FROM graphics
409WHERE svg_decoded LIKE '%<circle%';`}),"\n",(0,a.jsx)(t.h3,{children:"MongoDB Example"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`// MongoDB schema with Base64 SVG
410const GraphicSchema = new mongoose.Schema({
411name: String,
412svgBase64: String,
413// Virtual field for decoded SVG
414svgDecoded: {
415  type: String,
416  get: function() {
417    if (!this.svgBase64) return null;
418    const base64 = this.svgBase64.replace(/^data:image/svg+xml;base64,/, '');
419    return Buffer.from(base64, 'base64').toString('utf-8');
420  }
421},
422metadata: {
423  width: Number,
424  height: Number,
425  elements: Number
426}
427});
428
429// Middleware to extract metadata on save
430GraphicSchema.pre('save', function(next) {
431if (this.svgBase64) {
432  const svg = this.svgDecoded;
433  this.metadata = extractSVGMetadata(svg);
434}
435next();
436});`}),"\n",(0,a.jsx)(t.h2,{children:"Security Considerations"}),"\n",(0,a.jsxs)(i.Fc,{className:"my-6 border-red-200 bg-red-50",children:[(0,a.jsx)(h.A,{className:"h-4 w-4"}),(0,a.jsx)(i.TN,{children:(0,a.jsxs)(t.p,{children:[(0,a.jsx)("strong",{children:"Security Warning:"})," Always sanitize decoded SVGs before rendering. SVGs can contain JavaScript, external references, and other potentially malicious content. Never trust user-supplied Base64 without validation."]})})]}),"\n",(0,a.jsx)(t.h3,{children:"Security Best Practices"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`// Comprehensive SVG sanitization
437function secureSVGDecode(base64Input, options = {}) {
438const decoded = atob(base64Input.replace(/^data:image/svg+xml;base64,/, ''));
439
440// Security checks
441const securityViolations = [];
442
443// Check for scripts
444if (/<script/i.test(decoded)) {
445  securityViolations.push('Contains script tags');
446}
447
448// Check for external references
449if (/xlink:hrefs*=s*["'](?!#)/i.test(decoded)) {
450  securityViolations.push('Contains external references');
451}
452
453// Check for data URIs in href
454if (/hrefs*=s*["']data:/i.test(decoded)) {
455  securityViolations.push('Contains data URI in href');
456}
457
458// Check for event handlers
459const eventHandlers = /onw+s*=/gi;
460if (eventHandlers.test(decoded)) {
461  securityViolations.push('Contains event handlers');
462}
463
464if (securityViolations.length > 0 && !options.allowUnsafe) {
465  throw new SecurityError('SVG contains potentially unsafe content', {
466    violations: securityViolations
467  });
468}
469
470// Sanitize if requested
471if (options.sanitize) {
472  return sanitizeSVG(decoded);
473}
474
475return decoded;
476}`}),"\n",(0,a.jsx)(t.h2,{children:"Performance Optimization"}),"\n",(0,a.jsx)(t.h3,{children:"Batch Processing"}),"\n",(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4 font-mono text-sm",children:`// Efficient batch Base64 to SVG conversion
477class BatchBase64Converter {
478constructor() {
479  this.worker = new Worker('/workers/base64-decoder.js');
480}
481
482async convertBatch(base64Array) {
483  // Process in parallel using Web Workers
484  const chunks = this.chunkArray(base64Array, 10);
485  const results = await Promise.all(
486    chunks.map(chunk => this.processChunk(chunk))
487  );
488  
489  return results.flat();
490}
491
492processChunk(chunk) {
493  return new Promise((resolve) => {
494    this.worker.postMessage({ action: 'decode', data: chunk });
495    this.worker.onmessage = (e) => resolve(e.data);
496  });
497}
498
499chunkArray(array, size) {
500  const chunks = [];
501  for (let i = 0; i < array.length; i += size) {
502    chunks.push(array.slice(i, i + size));
503  }
504  return chunks;
505}
506}`}),"\n",(0,a.jsx)(t.h2,{children:"Common Use Cases & Examples"}),"\n",(0,a.jsxs)(c.Tabs,{defaultValue:"api",className:"my-8",children:[(0,a.jsxs)(c.TabsList,{children:[(0,a.jsx)(c.TabsTrigger,{value:"api",children:"API Integration"}),(0,a.jsx)(c.TabsTrigger,{value:"email",children:"Email Graphics"}),(0,a.jsx)(c.TabsTrigger,{value:"database",children:"Database Recovery"})]}),(0,a.jsx)(c.TabsContent,{value:"api",children:(0,a.jsxs)(o.Zp,{className:"p-4",children:[(0,a.jsx)("h4",{className:"font-bold mb-3",children:"REST API Icon Fetching"}),(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded text-sm overflow-x-auto",children:`// Fetch and decode company logos from API
507async function loadCompanyLogos() {
508const response = await fetch('/api/companies/logos');
509const companies = await response.json();
510
511const converter = new Base64ToSVGConverter();
512
513return companies.map(company => ({
514  ...company,
515  logo: converter.decode(company.logoBase64),
516  logoUrl: converter.createDownloadLink(
517    converter.decode(company.logoBase64),
518    \`\${company.name}-logo.svg\`
519  )
520}));
521}`})]})}),(0,a.jsx)(c.TabsContent,{value:"email",children:(0,a.jsxs)(o.Zp,{className:"p-4",children:[(0,a.jsx)("h4",{className:"font-bold mb-3",children:"Email Signature Extraction"}),(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded text-sm overflow-x-auto",children:`// Extract logo from email signature
522function extractEmailLogo(emailHTML) {
523const parser = new DOMParser();
524const doc = parser.parseFromString(emailHTML, 'text/html');
525
526// Find signature area
527const signature = doc.querySelector('.email-signature, .signature');
528if (!signature) return null;
529
530// Look for Base64 SVG images
531const img = signature.querySelector('img[src^="data:image/svg"]');
532if (!img) return null;
533
534const base64 = img.src;
535return new Base64ToSVGConverter().decode(base64);
536}`})]})}),(0,a.jsx)(c.TabsContent,{value:"database",children:(0,a.jsxs)(o.Zp,{className:"p-4",children:[(0,a.jsx)("h4",{className:"font-bold mb-3",children:"Bulk Database Migration"}),(0,a.jsx)("pre",{className:"bg-slate-900 text-gray-100 p-4 rounded text-sm overflow-x-auto",children:`// Migrate Base64 stored SVGs to files
537async function migrateDatabaseSVGs() {
538const records = await db.query(
539  'SELECT id, svg_base64 FROM graphics WHERE svg_file IS NULL'
540);
541
542const converter = new Base64ToSVGConverter();
543
544for (const record of records) {
545  const svg = converter.decode(record.svg_base64);
546  const filename = \`graphic-\${record.id}.svg\`;
547  
548  // Save to file system
549  await fs.writeFile(\`./assets/\${filename}\`, svg);
550  
551  // Update database
552  await db.query(
553    'UPDATE graphics SET svg_file = $1 WHERE id = $2',
554    [filename, record.id]
555  );
556}
557}`})]})})]}),"\n",(0,a.jsx)(t.h2,{children:"Conclusion"}),"\n",(0,a.jsx)(t.p,{children:"Base64 to SVG conversion is essential for modern web development, enabling seamless integration with APIs, email systems, and databases. Our converter handles all common encoding formats, validates SVG structure, and provides security sanitization to ensure safe rendering."}),"\n",(0,a.jsx)(t.p,{children:"Whether you're processing API responses, extracting email graphics, or recovering database-stored images, our Base64 to SVG converter provides the reliability and performance needed for production applications."}),"\n",(0,a.jsxs)(o.Zp,{className:"p-6 my-8 bg-gradient-to-r from-purple-500 to-blue-500 text-white",children:[(0,a.jsx)("h3",{className:"text-xl font-bold mb-4",children:"\uD83D\uDD13 Decode Your Base64 SVGs"}),(0,a.jsx)("p",{className:"mb-4",children:"Convert Base64 strings and data URIs to clean SVG files instantly."}),(0,a.jsxs)("div",{className:"flex gap-4",children:[(0,a.jsx)("button",{className:"px-6 py-2 bg-white text-purple-600 rounded-lg hover:bg-gray-100",children:(0,a.jsx)(t.p,{children:"Start Decoding"})}),(0,a.jsx)("button",{className:"px-6 py-2 border-2 border-white rounded-lg hover:bg-white/10",children:(0,a.jsx)(t.p,{children:"API Documentation"})})]})]})]})}function x(e={}){let{wrapper:t}={...(0,r.R)(),...e.components};return t?(0,a.jsx)(t,{...e,children:(0,a.jsx)(u,{...e})}):u(e)}},54213:(e,t,s)=>{s.d(t,{A:()=>a});let a=(0,s(19946).A)("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]])}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.