Convert Base64 String to Image

Convert base64 string to image

This assumes a few things, that you know what the output file name will be and that your data comes as a string. I'm sure you can modify the following to meet your needs:

// Needed Imports
import java.io.ByteArrayInputStream;
import sun.misc.BASE64Decoder;

def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';

// tokenize the data
def parts = sourceData.tokenize(",");
def imageString = parts[1];

// create a buffered image
BufferedImage image = null;
byte[] imageByte;

BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();

// write the image to a file
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);

Please note, this is just an example of what parts are involved. I haven't optimized this code at all and it's written off the top of my head.

How to convert base64 string to image?

Try this:

import base64
imgdata = base64.b64decode(imgstring)
filename = 'some_image.jpg' # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
f.write(imgdata)
# f gets closed when you exit the with statement
# Now save the value of filename to your database

How to convert BASE64 string into Image with Flutter?

You can convert a Uint8List to a Flutter Image widget using the Image.memory constructor. (Use the Uint8List.fromList constructor to convert a List to Uint8List if necessary.) You can use BASE64.encode to go the other way.

Here's some sample code.

screenshot

import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
runApp(new MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
theme: new ThemeData.dark(),
home: new MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
String _base64;

@override
void initState() {
super.initState();
(() async {
http.Response response = await http.get(
'https://flutter.io/images/flutter-mark-square-100.png',
);
if (mounted) {
setState(() {
_base64 = BASE64.encode(response.bodyBytes);
});
}
})();
}

@override
Widget build(BuildContext context) {
if (_base64 == null)
return new Container();
Uint8List bytes = BASE64.decode(_base64);
return new Scaffold(
appBar: new AppBar(title: new Text('Example App')),
body: new ListTile(
leading: new Image.memory(bytes),
title: new Text(_base64),
),
);
}
}

However, it's generally a bad idea to store large blobs of binary data in your database. It's not playing to the strengths of Firebase realtime database and you will end up wasting bandwidth transmitting data you don't need as well as unnecessary encoding and decoding. You should use the firebase_storage plugin instead, storing the path or download URL of the image in the database.

Convert base64 String to an Image that's compatible with OpenCV

I've been struggling with this issue for a while now and of course, once I post a question - I figure it out.

For my particular use case, I needed to convert the string into a PIL Image to use in another function before converting it to a numpy array to use in OpenCV. You may be thinking, "why convert to RGB?". I added this in because when converting from PIL Image -> Numpy array, OpenCV defaults to BGR for its images.

Anyways, here's my two helper functions which solved my own question:

import io
import cv2
import base64
import numpy as np
from PIL import Image

# Take in base64 string and return PIL image
def stringToImage(base64_string):
imgdata = base64.b64decode(base64_string)
return Image.open(io.BytesIO(imgdata))

# convert PIL Image to an RGB image( technically a numpy array ) that's compatible with opencv
def toRGB(image):
return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

Converting base64 to image | Not working | Flutter

Well, this got resolved when I wrapped SfPdfViewer.memory(bytes) inside a Container. Though, not sure why it wasn't working without a Container.

The whole solution:

Uint8List bytes = base64.decode(pdf);
return Container(
child: SfPdfViewer.memory(bytes),
);

Package used : syncfusion_flutter_pdfviewer

How to convert base64 string into image in kotlin android

You can use this code to decode: -

val imageBytes = Base64.decode(base64String, Base64.DEFAULT)
val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length)
imageView.setImageBitmap(decodedImage)

Convert base64 string to image and save

The start of the string, up to the first comma, is information added by POSTing the data, and as such is not part of the base64 encoding of your file. So remove it before decoding.

Decoding a base64 image

As there can not be , in base64 string and also it is the separator, so the image part is right after the comma:

byte[] imgBytes  = Convert.FromBase64String(base64string.Split(',')[1]);


Related Topics



Leave a reply



Submit