Send a file to a API in Java - java

I'm using the library QRCodeWriter that create a QR and send it to an API.
The issue is that I have variable os where the image is stored, but I can not able to add it to MultipartEntity to send it (commented line).
The error is: incompatible types: ByteArrayOutputStream cannot be converted to ContentBody entity.addPart("file", os)
I tried a lot of code to convert the image without success.
Any help will be apreciated
String url = "https://apiURL.com";
String accessToken = "123456789";
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = writer.encode("https://www.google.com/", BarcodeFormat.QR_CODE, 350, 350);
BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.setUseCache(false);
ImageIO.write(image,"png",os);
context.log(os.toString());
basicIO.write("TestData");
MultipartEntity entity = new MultipartEntity();
//entity.addPart("file", os);
HttpResponse returnResponse = Request.Post(url).addHeader("Authorization", accessToken).body(entity).execute().returnResponse();
context.log("Response status: " + returnResponse.getStatusLine().getStatusCode());
context.log(EntityUtils.toString(returnResponse.getEntity()));

It works changing:
entity.addPart("file", os);
to:
entity.addPart("file", new ByteArrayBody(os.toByteArray(), "qr.png"));

Related

How to generate UPC or EAN bar code with xzing java library

I found the next code that generates QRCODE from a string using google zxing library
String textToCodify = "1234567891234";
QRCodeWriter barcodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = barcodeWriter.encode(textToCodify, BarcodeFormat.EAN_13, 200, 200);
File outputfile = new File("image.jpg");
BufferedImage code = MatrixToImageWriter.toBufferedImage(bitMatrix);;
ImageIO.write(code, "jpg", outputfile);
But when I've tried to generate UPC or EAN code I've got some exception raised.
java.lang.IllegalArgumentException: Can only encode QR_CODE, but got EAN_13
at com.google.zxing.qrcode.QRCodeWriter.encode(QRCodeWriter.java:59)
at com.google.zxing.qrcode.QRCodeWriter.encode(QRCodeWriter.java:44)
at workWithBarCode.Test.generateQRCodeImage(Test.java:43)
at workWithBarCode.Test.main(Test.java:23)
Can some one help.
I found the solution: just use EAN13Writer in place of QRCodeWriter
String textToCodify = "123456789123";
EAN13Writer eAN13Writer = new EAN13Writer();
//QRCodeWriter barcodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = eAN13Writer.encode(textToCodify, BarcodeFormat.EAN_13, 210, 100);
File outputfile = new File("image.jpg");
BufferedImage code = MatrixToImageWriter.toBufferedImage(bitMatrix);;
ImageIO.write(code, "jpg", outputfile);

Download image from SVG with Jersey

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.

Send Byte array as file in using http client in java

We have byte array of file and we want to upload it as file.
FileBody only gets File as parameter but we have a array of bytes.
One solution is to save byte array into file and then send it
but it is not appropriate for me.
byte b[]= new byte[1000];
//fill b
MultipartEntity form = new MultipartEntity();
form.addPart("file", new FileBody(/* b? */));
thanks.
You can do something like
HttpClient client=null;
byte b[]= new byte[1000];
MultipartEntity form = new MultipartEntity();
ContentBody cd = new InputStreamBody(new ByteArrayInputStream(b), "my-file.txt");
form.addPart("file", cd);
HttpEntityEnclosingRequestBase post = new HttpPost("");//If a PUT request then `new HttpPut("");`
post.setEntity(form);
client.execute(post);
You can use ByteArrayBody instead InputStreamBody or FileBody.
HttpClient client=null;
byte b[]= new byte[1000];
MultipartEntity form = new MultipartEntity();
ContentBody cd = new ByteArrayBody(b, "my-file.txt");
form.addPart("file", cd);
HttpEntityEnclosingRequestBase post = new HttpPost("");
post.setEntity(form);
client.execute(post);

Android post high res image running out of memory

Good day fellow developers.
I'm busy for android to upload images from a app.
I also got it working (code will follow below).
But when i send large images (10 megapixels) my app crashes with an out-of-memory exception.
A solution for this is to use compression but what if i want to send the full size image?
I think perhaps something with a stream but i'm not familair with streams. Perhaps urlconnection might help to but i really have no idea.
I give the filename the name File[0 to 9999].jpg
The post value with the image date is called Filedata
I give a UID for the post value dropboxid
The code below works but i would love to solve my problem that prevents me from sending high res images.
kind regards
try
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
HttpPost postRequest = new HttpPost(URL_SEND);
ByteArrayBody bab = new ByteArrayBody(data, "File" + pad(random.nextInt(9999) + 1) + ".jpg");
MultipartEntity reqEntity = new multipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("Filedata", bab);
reqEntity.addPart("dropboxId", new StringBody(URLEncoder.encode(uid)));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while((sResponse = reader.readLine()) != null)
{
s = s.append(sResponse);
}
if(d) Log.i(E, "Send response:\n" + s);
}
catch (Exception e)
{
if(d) Log.e(E, "Error while sending: " + e.getMessage());
return ERROR;
}
When using ByteArrayOutputStream and then calling #toByteArray() you've effectively doubled the amount of memory the JPEG is using. ByteArrayOutputStream keeps an internal array with the encoded JPEG and when you call #toByteArray() it allocates a new array & copies the data from the internal buffer.
Consider encoding large bitmaps to a temporary file & using FileOutputStream and FileInputStream to encode and send the image.
Without "uploading" - your app survives "nicely" with the just the huge bitmap in memory I assume?
Edit: FileBody
File img = new File(this is where you put the path of your image)
ContentBody cb = new FileBody(img, "File" + pad(random.nextInt(9999) + 1) + ".jpg", "image/jpg", null);
MultipartEntity reqEntity = new multipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("Filedata", cb);
reqEntity.addPart("dropboxId", new StringBody(URLEncoder.encode(uid)));

how to httpput the image on a remote server from android

I have tried with following code , but its not working
File file= new File(filename);
byte[] data = new byte[(int) file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL("http://www.example.com/resource");
HttpClient client = new DefaultHttpClient();
HttpPut put= new HttpPut(url);
for (int i = 0; i pairs = new ArrayList();
pairs.add(new BasicNameValuePair("Data", data));
put.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(put);
I could not able to PUT the data on the server I have also tried with HttpsURLConnection but its getting uploaded.
After setting the content length I am able to do HTTP put , with the help of HttpURLConnection as follows https.setRequestProperty("Content-Type", "image/jpeg");
https.setRequestProperty("Content-Length", "" + file.length());

Categories

Resources