How do I read an image into a base64 encoded string by its ImageReader?
Here's example source code using HtmlUnit. I want to get the base64 String of img:
WebClient wc = new WebClient();
wc.setThrowExceptionOnFailingStatusCode(false);
wc.setThrowExceptionOnScriptError(false);
HtmlPage p = wc.getPage("http://flickr.com");
HtmlImage img = (HtmlImage) p.getByXPath("//img").get(3);
System.out.println(img.getImageReader().getFormatName());
The HtmlUnit's HtmlImage#getImageReader() returns javax.imageio.ImageReader which is part of standard Java 2D API. You can get an BufferedImage out of it which you in turn can write to an OutputStream of any flavor using ImageIO#write().
The Apache Commons Codec has a Base64OutputStream which you can just decorate your OutputStream with.
HtmlImage img = (HtmlImage) p.getByXPath("//img").get(3);
ImageReader imageReader = img.getImageReader();
BufferedImage bufferedImage = imageReader.read(0);
String formatName = imageReader.getFormatName();
ByteArrayOutputStream byteaOutput = new ByteArrayOutputStream();
Base64OutputStream base64Output = new base64OutputStream(byteaOutput);
ImageIO.write(bufferedImage, formatName, base64output);
String base64 = new String(byteaOutput.toByteArray());
Or if you want to write it to file directly:
// ...
FileOutputStream fileOutput = new FileOutputStream("/base64.txt");
Base64OutputStream base64Output = new base64OutputStream(fileOutput);
ImageIO.write(bufferedImage, formatName, base64output);
I'm not quite sure what exactly you want.
But what about creating your own Reader (see javax.imageio.stream.ImageInputStreamImpl), containing the Base64-stuff?
Maybe this external free Base64Encoder can help you out.
Something that could be used like this in the end?
WebClient wc = new WebClient();
wc.setThrowExceptionOnFailingStatusCode(false);
wc.setThrowExceptionOnScriptError(false);
HtmlPage p = wc.getPage("http://flickr.com");
HtmlImage img = (HtmlImage) p.getByXPath("//img").get(3);
MyBase64EncodingReader reader = new MyBase64EncodingReader(img);
System.out.println(reader.toString());
You could use one of the encodeBase64 methods
from apache commons codec.
and create a string from the resulting byte array using the String(bytes[]) constructor.
Related
i want to convert my png image file into svg and store in file system, i not found any apropriate answer if anyone have the solution please share.
i use below code but not work
SVGTranscoder t = new SVGTranscoder();
t.addTranscodingHint(SVGTranscoder.KEY_FORMAT, true);
String svgURI = new File(inputFilePath).toURL().toString();
InputStream inputStream = new FileInputStream(inputFilePath);
Reader inputStreamReader = new InputStreamReader(inputStream);
TranscoderInput input = new TranscoderInput(inputStreamReader);
OutputStream ostream = new FileOutputStream(outputFilePath);
Writer outputStreamWriter = new OutputStreamWriter(ostream);
TranscoderOutput output = new TranscoderOutput(outputStreamWriter);
t.transcode(input, output);
ostream.flush();
ostream.close();
System.exit(0);
Try this:
Converter converter = new Converter("input.png");
// Prepare conversion options for target format SVG
ConvertOptions convertOptions = new FileType().fromExtension("svg").getConvertOptions();
// Convert to SVG format
converter.convert("output.svg", convertOptions);
I am uploading a jpg to a spring controller endpoint. The image is uploaded as Base64 image/jpg which comes in as a MultipartFile. I am decoding the inputstream using Base64Decoder which seems to decode it ok but when I turn it into an InputStream to write it out to disk I can see it's been modified (according to what I can see in the debugger). When I save the file and open it it says it's an unsupported file type.
I took the multipart inputstream and wrote it directly to disk and I see the base64 encoding in notepad.
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QBgRXhpZgAASUkqAAgAAAACADEBAgAHAAAAJgAAAGmHBAABAAAALgAAAAAAAABHb29nbGUAAAMAAJAHAAQAAAAwMjIwAqAEAAEAAAAACAAAA6AEAAEAAAAABgAAAAAAAP/bAIQAAwICCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCggKCgoKCgoICAgKCgoICAgICgoICAgKCgoICA0NCggNCAgKCAEDBAQGBQYIBgYICA0ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI/8AAEQgGAAgAAwEiAAIRAQMRAf/EAB0AAAIDAQEBAQEAAAAAAAAAAAMEAgUGAQAHCAn/xABJEAABAwIDBgQFBAIBAwMCAA8BAAIRAyEEMUEFElFhcfAGgZGhEyKxwdEHMuHxFEJSFSNiCDNyFoKSFyRDU6LCCTRjRHOy0uL/xAAbAQEBAQEBAQEBAAAAAAAAAAAAAQIDBAUGB//EACoRAQEBAQACAwADAAEEAwEBAQABEQIDcRIhMQQTsVEUIjJBBWGBwUIj/9oADAMBAAIRAxEAPwCgrFsRw4ZfWEs2FXUN4C7p4c10702ML4/M+p6jhzfqep/i4p0uS9Vtw8vddwRkX7t+ck1TdElWusVNVsRY3K1ngx2YFsz5rMYytJHX+7rSeDWGf6XHqf8A0938eZ02zK8LlWoMzwP9LwCV2jxC81j7kswTAYsE2Xto1OAzVPslvzHT8K8LV
Here's my controller and my code:
#PostMapping(value = "/saveBlueprintOrder")
public ResponseEntity<?> saveBlueprintOrder(#RequestParam MultipartFile blueprint,
#RequestParam(required = false) MultipartFile coversheet,
#RequestParam(required = false) MultipartFile logo,
#ModelAttribute BlueprintOrder blueprintOrder) {
if(coversheet != null) {
BASE64Decoder decoder1 = new BASE64Decoder();
byte[] imageBytes = decoder1.decodeBuffer(coversheet.getInputStream());
InputStream bis = new ByteArrayInputStream(imageBytes);
BufferedImage image = ImageIO.read(bis);
ImageIO.write(image, "jpg", new File("C:\\Users\\i58287\\Downloads\\coversheet.jpg"));
OutputStream stream = new FileOutputStream("C:\\Users\\i58287\\Downloads\\coversheet-test.jpg");
stream.write(imageBytes);
stream.close();
I just need to be able to translate this image to an inputstream so I can check the image locally in addition I need to send it to another api as such. What am I missing that's causing this image to be un-openable? Thanks for any help!
PS: I've done a lot of combinations so this is showing a couple options I have tried, BufferedImage image = ImageIO.read(bis) keeps returning a null image.
Ok so I don't know WHY this is what I had to do but I ended up saving my byte[] as a String and cut off the pre-pended
data:image/jpeg;base64
Then I decoded it into an InputStream. Anyone know why I had to do this?
Here's the code:
String imageBytes = new String(coversheet.getBytes(), StandardCharsets.UTF_8);
String imageDataBytes = imageBytes.substring(imageBytes.indexOf(",") + 1);
InputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(imageDataBytes.getBytes()));
BufferedImage image = ImageIO.read(stream);
ImageIO.write(image, "jpg", new File("C:\\Users\\i58287\\Downloads\\coversheet-test.jpg"));
I want to extract PDF context into a String. I've done that previously using PDFBox but it doesn't support a lot of fonts I have in my PDFs.
Decided to use iText instead. How can I do that using getByteStream from a blob rather than a file on disk?
Blob blobPdf = ...;
File outputFile = new File("/tmp/blah/whatever.pdf");
FileOutputStream fout = new FileOutputStream(outputFile);
IOUtils.copy(blobPdf.getBinaryStream(), fout);
I want this sort of logic but insert the context into the String variable instead. How can I do that?
#EDIT
This is my attempt
InputStream is = resultSet.getBinaryStream(3);
PdfReader reader = new PdfReader(is);
String text = PdfTextExtractor.getTextFromPage(reader, 1);
System.out.println(text);
I'm reading a file that has an array of bytes. I downloaded the Apache Commons IO library to use the FileUtils' method readFileToByteArray
File file = new File("/home/username/array.txt");
FileUtils fu = new FileUtils();
byte[] array = FileUtils.readFileToByteArray(file);
I want to convert the array of bytes to an Image.
ByteArrayInputStream bis = new ByteArrayInputStream(array);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("gif");
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Image image = reader.read(0, param); // this line is the problem
When the code goes to the referred line, it throws an Exception saying
javax.imageio.IIOException: Unexpected block type 128!
I don't know what this exception means, therefore, I don't know how to fix it.
Any further information that could be helpful just need to be requested.
Thanks
I've tried your code on this file and it works fine.
What's the format of your array.txt? readFileToByteArray() expects a binary format, and your image reader will further expect it to be a GIF file.
Once you have byte[] you can use ImageIO to write it to BufferedImage.
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(array));
ImageIO.write(bImageFromConvert, "gif", new File("c:/test.gif"));
That code means the reader couldn't decipher the metadata on the image file. Make sure the right file is getting read and it's well formed. Or it may be expecting a different file type.
without byte[] i feel this will be good for multipart file transfer,for this we need apache common jar files
final FileOutputStream output = new FileOutputStream("D:\\Dir\\"+ request.getParameter("imageName") + ".jpg");
IOUtils.copy(request.getPart("file").getInputStream(), output);
output.close();
I'm trying to create a BufferedImage from a ByteArrayInputStream with:
byte[] imageData = getData(imageFile); // returns file as byte[]
InputStream inputStream = new ByteArrayInputStream(imageData);
String format = getFormatName(inputStream);
BufferedImage img = ImageIO.read(inputStream);
But img is always null. The input stream is valid (since I use it before to get the image format).
What could be making ImageIO return null? Do I need to use flush or close in any place?
Your call to getFormatName consumes the inputStream, so the stream pointer is at the end of the byte array. Any try to read from that stream will tell that it's at the end of the 'file'. You need to reset the stream (or create a new one) before you hand it over to the ImageIO.read() method:
String format = getFormatName(new ByteArrayInputStream(imageData));
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData));