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 display Base64 images in HTML
My suspect is of course the actual Base64 data. Otherwise it looks good to me. See this fiddle where a similar scheme is working. You may try specifying the character set.
<div>
<p>Taken from wikpedia</p>
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
</div>
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.
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.
converting a base 64 string to an image and saving it
Here is an example, you can modify the method to accept a string parameter. Then just save the image object with image.Save(...).
public Image LoadImage()
{
//data:image/gif;base64,
//this image is a single pixel (black)
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
It is possible to get an exception A generic error occurred in GDI+.
when the bytes represent a bitmap. If this is happening save the image before disposing the memory stream (while still inside the using statement).
Fetch image from URL and convert it to base64 string - Flutter
Finally I found the solution using http package
import 'package:http/http.dart' as http;
Future<String> networkImageToBase64(String imageUrl) async {
http.Response response = await http.get(imageUrl);
final bytes = response?.bodyBytes;
return (bytes != null ? base64Encode(bytes) : null);
}
Example:
final imgBase64Str = await networkImageToBase64('IMAGE_URL');
print(imgBase64Str);
This is working perfectly for both mobile and web.
Get Base64 image dimension in python
Using the pillow library one can do:
import io
import PIL
from PIL import Image
imgdata = base64.b64decode(base64_str)
im = Image.open(io.BytesIO(imgdata))
width, height = im.size
Why can't I get a image (base64 string) to display
- Original Image was a jpeg
- I had to put it in a buffer first.
const buff = new Buffer(data.image, 'base64');
...
<Image style={styles.logo} src={{ data: buff, format: 'jpg' }} />
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
Image file size from data URI in JavaScript
If you want file size, simply decode your base64 string and check the length.
var src ="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP/// yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
var base64str = src.substr(22);var decoded = atob(base64str);
console.log("FileSize: " + decoded.length);
Related Topics
Escaping Column Names in Pdo Statements
PHP Strtotime +1 Month Adding an Extra Month
How to Apply a Function to an Array
Fatal Error: Class 'Mongodb\Driver\Manager' Not Found
New MySQLi(): How to Intercept an 'Unable to Connect' Error
Sort an Array with Special Characters in PHP
Using SQLite3 in PHP How to Count the Number of Rows in a Result Set
PHP Get Content of Http 400 Response
How to Easily Convert Dates from Utc via PHP
PHP Exec: Does Not Return Output
How to Use MySQLi_Query() in PHP
How to Take a Photo and Send to Http Post Request with Android
How to Send Multiple Attachment in Single Mail in PHP
Sort Xml via Attribute Value PHP
Can Anyone Get Access to My PHP Source Code
Getting the Full Url Including the Query String After Hash