I have some SVG string from highcharts and I want to download it as an image (PNG).
The conversion is done using PNGTranscoder (Batik)
#POST
public Response getChartImage() throws Exception{
String svg = "<svg xmlns:xlink..."; // can be ignored
svg = svgDocumentConvertAndRevert(svg); // can be ignored
TranscoderInput input = new TranscoderInput(new StringReader(svg));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(baos);
PNGTranscoder transcoder = new PNGTranscoder();
transcoder.transcode(input, output);
BufferedImage image = new BufferedImage(300, 500, 1);
ImageIO.write(image, "png", baos);
byte[] imageData = baos.toByteArray();
return Response.ok(imageData).build();
}
but what I'm getting is a bunch of text, something like
�PNG IHDR�#��E� cHRMz&��...
Tried with #Produces("image/*") but didn't work...
Can I not save it as an image (real file) and allow user to download it? Trying to avoid unnecessary effort..
Thanks!
You need to set the correct mime type for the response something like
response.setContentType("image/png");
where response is a ServletResponse object.
It was working, just that I was using Chrome's extension POSTman.
Related
I have a Spring MVC Web Service that returns an image as a byte array. The output is in json format. The format is png
Here's the code snippet for the image.
BufferedImage img = ImageIO.read(new File(caminho.replace("/", "//")));
imagem = ((DataBufferByte) img.getRaster().getDataBuffer
()).getData();
When I run the server, this is the output:
[{"id":0,"caminhoMDPI":null,"caminhoHDPI":"C:/Users/Marcos/Pictures/postos/drawable-
mdpi/esso_logo.png","caminhoXHDPI":null,"caminhoXXHDPI":null,"imagem":"AAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAA....]
Eventually, other symbols appear on the "imagem" field. I suppose this is right, but I'm not
sure.
On my Android app, I have a routine to download the image and store it as a blob in the database. I receive the json format and transform it into a class with jackson. I've logged the "imagem" field and it looks the same.
My problem is that I can't transform it into an image. Here's the code snippet:
byte[] img_bandeira = cursor.getBlob(cursor.getColumnIndex("img_bandeira"));
Bitmap bmpBandeira = BitmapFactory.decodeByteArray(img_bandeira, 0, img_bandeira.length);
ImageView ivBandeira = (ImageView) view.findViewById(R.id.ivBandeira);
ivBandeira.setImageBitmap(bmpBandeira);
All I get is a message: skImageDecoder::Factory returned null.
I've looked at other similar posts, tried to change some lines, but nothing happened. I don't know what's going on here. Thanks in advance.
I solved it. In the server, the image should be sent like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage img = ImageIO.read(new File(caminho.replace("/", "//")));
ImageIO.write(img, "png", baos);
baos.flush();
String base64String = Base64.encode(baos.toByteArray());
baos.close();
In my app, it should be read like this:
public static Bitmap getImage(byte[] imageArray) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageArray);
Bitmap bitmap = BitmapFactory.decodeStream(byteArrayInputStream);
return bitmap;
}
Thank you, everybody ;)
I need a dynamic solution to convert a unknown image format to .png in java.
Will .getType() help me out here, it seems only to return numbers.
The converted image should later be stored in a folder, but I guess that is easly done in the
ImageIO.write().
It's just that with converting an unknown image format that I have no idea how to approach.
This peace of code should do the magic:
File file = new File("unknown.type.pic");
ByteArrayInputStream bais = new ByteArrayInputStream(FileUtils.readFileToByteArray(file);
BufferedImage image = ImageIO.read(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
OutputStream outputStream = new FileOutputStream ("output.jpg");
baos.writeTo(outputStream);
Add missing try/catch/finally blocks.
I'm using a jQuery plugin called wPaint to allow users to draw their own image. I send the resulting image as a string to the server as a string which begins with
data:image/png;base64,
I tried the two approaches below but with both the approaches i'm not able to store the image.
Approach 1
String imageData = parameterParser.getStringParameter("image", "");
byte[] imgByteArray = Base64.decodeBase64(imageData.getBytes());
FileOutputStream fileOutputStream = new FileOutputStream("/home/arvind/Desktop/test.png");
fileOutputStream.write(imgByteArray);
fileOutputStream.close();
In this case the file is written but doesn't show the image. However, when i remove the file extension i get the string that was sent to the server (i.e. whatever is in imageData).
Approach 2
String imageData = parameterParser.getStringParameter("image", "");
byte[] imgByteArray = Base64.decodeBase64(imageData.getBytes());
InputStream in = new ByteArrayInputStream(imgByteArray);
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert, "png", new File("/home/arvind/Desktop/test.png"));
The BufferedImage bImageFromConvert is null so I get an exception (IllegalArgumentException) when the file is created.
The Base64 class is from the apache commons codec library and is version 1.2.
Is there something I'm doing wrong?
Initially I had sent the data to the server using the following code.
$.ajax({
url : '/campaign/holiImageUpload.action',
type : 'POST',
data : "image=" + $("#wPaint2").wPaint("image")
success :function(data){
}
});
Now i'm sending the data to the server using the following code
var imgData = $("#wPaint2").wPaint("image");
$.ajax({
url : '/campaign/holiImageUpload.action',
type : 'POST',
data : {image : imgData},
success :function(data){
}
});
In the server side this is the final code :
String imageData = parameterParser.getStringParameter("image", "");
try {
imageData = imageData.substring(22);
byte[] imgByteArray = Base64.decodeBase64(imageData.getBytes());
InputStream in = new ByteArrayInputStream(imgByteArray);
BufferedImage bufferedImage = ImageIO.read(in);
ImageIO.write(bufferedImage, "png", new File("/home/arvind/Desktop/test.png"));
catch(Exception ex){
ex.printStrackTrace();
}
It appears that you are trying to decode data:image/png'base64 along with your Base64 encoded data? You will want to remove that from the input string before you decode the Base64 data into image bytes.
Also, you don't want to decode the string as bytes... just as a string.
I need to create a barcode image in java using jasperreports, currently I'm doing this saving the image file on disk, but I need to do it without saving the image on disk. I need to create the barcode image in memory an then send it to iReport as a parameter.
This is what I have done:
Map<String, Object> parameters = new HashMap<String, Object>();
String imagePath = "\\\\netw\\barCode.jpg";
parameters.put("rutaCodigoBarrasVal", imagePath);
Barcode barCode = BarcodeFactory.createPDF417("1234567890");
barCode.setDrawingText(false);
barCode.setBarHeight(33);
barCode.setBarWidth(207);
FileOutputStream fOS = new FileOutputStream(imagePath);
BarcodeImageHandler.writeJPEG(barCode, fOS);
fOS.close();
What can I do?
You should first try to write the Barcode into a byte array or InputStream, looking at your library documentation.
JasperReports supports passing an image as a InputStream parameter, and draw that in the report.
InputStream imageStream = ...;
parametros.put("image", imageStream );
From JasperReports, receive that parameter as java.io.InputStream, then draw it with an image widget and the following properties:
Image Expression: $P{image}
Expression Class: java.io.InputStream
I hope it helps.
Finally this is what I did using barcode4j library:
ByteArrayOutputStream os = new ByteArrayOutputStream();
PDF417Bean barCode = new PDF417Bean();
boolean antiAlias = false;
int orientation = 0;
int dpi = 300;
BitmapCanvasProvider canvas = new BitmapCanvasProvider(dpi, BufferedImage.TYPE_BYTE_BINARY, antiAlias, orientation);
BarcodeDimension dim = new BarcodeDimension(207, 42);
canvas.establishDimensions(dim);
barCode.setColumns(7);
barCode.generateBarcode(canvas, codeToConvert);
canvas.finish();
String mime = MimeTypes.MIME_JPEG;
os = new ByteArrayOutputStream();
final BitmapEncoder encoder = BitmapEncoderRegistry.getInstance(mime);
encoder.encode(canvas.getBufferedImage(), os, mime, dpi);
fis = new ByteArrayInputStream(os.toByteArray());
I tried to create image from BLOB. I try following code but it is not working at step:
ImageIO.write(image, "JPG", iio);)
image is null. Please give me any suggestion.
byte[] imgData = null;
if (rs.next ())
{
Blob img = rs.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
File f1 = new File(fillFilePath); //fillFilePath = path where image want to store
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imgData));
ImageOutputStream iio = ImageIO.createImageOutputStream(f1);
ImageIO.write(image, "JPG", iio);
}
How to create image from BLOB using ImageIO?
From the JavaDoc on ImageIO.read(InputStream):
If no registered ImageReader claims to be able to read the resulting stream, null is returned.
It seems your blob doesn't represent an image format that ImageIO is able to understand. What format does the image stored in the blob have?
Below code works for me. I am able to retrieve BLOB(oracle)/binary(hive) from hive:
InputStream is=rs.getBinaryStream(1);
toImage(is,"C:\\hive_image.png");
public void toImage(InputStream is,String imagePath) throws IOException
{
BufferedImage bufferedImage=ImageIO.read(is);
ImageIO.write(bufferedImage, "png", new File(imagePath));
}