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
Convert base64 string to JPG
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"/>
Convert base64 string to image in Android
//encode image(from image path) to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeFile(pathOfYourImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//encode image(image from drawable) to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourDrawableImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
Convert base64 string to image at server side in java
Your code looks fine. I can suggest however some more debugging steps for you.
- Encode your file manually using, for example, this webpage
- Compare if
String base64
contains exact same content like you've got seen on the page. // if something wrong here, your request is corrupted, maybe some encoding issues on the frontend side? - See file content created under
./src/main/resources/demo.jpg
and compare content (size, binary comparison) // if something wrong here you will know that actually save operation is broken
Remarks:
- Did you try to do
.flush()
before close? - Your code in current form might cause resource leakage, have a look at try-with-resources
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.
How to convert a Base64 string into a Bitmap image to show it in a ImageView?
You can just basically revert your code using some other built in methods.
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
C# Base64 String to JPEG Image
So with the code you have provided.
var bytes = Convert.FromBase64String(resizeImage.Content);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes ,0, bytes.Length);
imageFile.Flush();
}
Related Topics
How to Remove Nan from List Python/Numpy
How to Do a Conditional Count After Groupby on a Pandas Dataframe
How to Remove/Delete a Virtualenv
How to Limit a Number to Be Within a Specified Range (Python)
Python: Fastest Way to Compare Arrays Elementwise
How to Count Occurrences of Key in List of Dictionaries
How to Run Two Python Scripts Simultaneously from a Master Script
Add N Empty Rows in a Dataframe
How to Use Variables in SQL Statement in Python
How to Map the Differences Between Two Strings
Filtering the Dataframe Based on the Column Value of Another Dataframe
How to Add List into a New Column in CSV - Python
Convert Number Strings With Commas in Pandas Dataframe to Float
Check If a Specific Class and Value Exist in HTML Using Beautifulsoup Python
Get Only Unique Words from a Sentence in Python
Python - Having Trouble Opening a File With Spaces
Opening a Word Document That Has a Password Using Docx Library