Convert Base64 String to an Image File

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.

Convert Base64 string to an image file?

The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.

function base64_to_jpeg($base64_string, $output_file) {
// open the output file for writing
$ifp = fopen( $output_file, 'wb' );

// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );

// we could add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode( $data[ 1 ] ) );

// clean up the file resource
fclose( $ifp );

return $output_file;
}

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

Convert base64 string to JPG

You're passing your io.Reader to png.Decode(), which begins consuming the reader, only to discover that the input is not a valid PNG, so returns an error.

Then your partly-consumed reader is passed to jpeg.Decode(), which reads the data not yet read, which is not a valid JPEG, and returns the error you observe.

You need to create a new reader for each decoder:

pngI, errPng := png.Decode(bytes.NewReader(unbased))

// ...

jpgI, errJpg := jpeg.Decode(bytes.NewReader(unbased))

Or better yet, consider the MIME type, and only call the proper decoder:

switch strings.TrimSuffix(image[5:coI], ";base64") {
case "image/png":
pngI, err = png.Decode(res)
// ...
case "image/jpeg":
jpgI, err = jpeg.Decode(res)
// ...
}

Base64 image string into image file using PHP

I figure it out the solution.

        $pathwithfile = 'your file path with image name';//e.g '/uploads/test.jpg'
$ifp = fopen( $pathwithfile, 'wb' );
// split the string on commas // $data[ 0 ] == "data:image/png;base64" // $data[ 1 ] == <actual base64 string> $data = explode( ',', $imagedata ); $success = fwrite( $ifp, base64_decode( $data[ 1 ] ) ); // clean up the file resource fclose( $ifp );

How to convert Base64 String to javascript file object like as from file input form?

Way 1: only works for dataURL, not for other types of url.

 function dataURLtoFile(dataurl, filename) {         var arr = dataurl.split(','),            mime = arr[0].match(/:(.*?);/)[1],            bstr = atob(arr[1]),             n = bstr.length,             u8arr = new Uint8Array(n);                    while(n--){            u8arr[n] = bstr.charCodeAt(n);        }                return new File([u8arr], filename, {type:mime});    }        //Usage example:    var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');    console.log(file);

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 Image in Java

I'm worried about that you need to decode only the base64 string to get the image bytes, so in your

"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVI..."

string, you must get the data after data:image\/png;base64,, so you get only the image bytes and then decode them:

String imageDataBytes = completeImageData.substring(completeImageData.indexOf(",")+1);

InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));

This is a code so you understand how it works, but if you receive a JSON object it should be done the correct way:

  • Converting the JSON string to a JSON object.
  • Extract the String under data key.
  • Make sure that starts with image/png so you know is a png image.
  • Make sure that contains base64 string, so you know that data must be decoded.
  • Decode the data after base64 string to get the image.

Convert base64 string to PNG image in android

Use this

    byte[] decodedString = Base64.decode(imageString, Base64.DEFAULT);
// Bitmap Image
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

String filename = "MyImage.png";
File file= Environment.getExternalStorageDirectory();
File dest = new File(file, filename);

try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

Required Permission in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

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).



Related Topics



Leave a reply



Submit