How to convert blob into .png and send it via firebase notification? - java

I have a problem when I try to send .png image via firebase service. Notification works fine and it comes to my phone, but, without image. Also, I've tried putting a direct link to the image from internet but when I tried to convert blob from database into .png and send it like that It doesnt send picture. I guess that I am not sending the image the right way?
Here is my controller code below:
Java
Company company = companyService.findCompanyByName(systemUserService.findByUsername(principal.getName()).getCompany().getName());
Notification notify = notificationService.findByName(name);
System.out.println("Title: " + notify.getName());
System.out.println("Message: " + notify.getText());
JSONObject body = new JSONObject();
body.put("to", "/topics/" + TOPIC);
body.put("priority", "high");
JSONObject notification = new JSONObject();
notification.put("title", notify.getName());
notification.put("body", notify.getText());
notification.put("sound", "default");
try {
byte[] aByteArray = company.getLogo();
int width = 1;
int height = 2;
DataBuffer buffer = new DataBufferByte(aByteArray, aByteArray.length);
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[] {0, 1, 2}, (Point)null);
ColorModel cm = new ComponentColorModel(ColorModel.getRGBdefault().getColorSpace(), false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
BufferedImage image = new BufferedImage(cm, raster, true, null);
ImageIO.write(image, "png", new File("image.png"));
notification.put("image", image);
} catch (IOException e) {
e.printStackTrace();
}
JSONObject data = new JSONObject();
data.put("Key-1", "JSA Data 1");
data.put("Key-2", "JSA Data 2");
body.put("notification", notification);
body.put("data", data);
HttpEntity<String> request = new HttpEntity<>(body.toString());
CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);
CompletableFuture.allOf(pushNotification).join();
try {
String firebaseResponse = pushNotification.get();
return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);

Try something like this :
Download image from URL and convert to Base64 encoded String that can be JSONified.
public String jsonifyImage(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
Bitmap bMap = BitmapFactory.decodeStream(connection.getInputStream());
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
bMap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
byte[] byteArr = oStream.toByteArray();
return Base64.getEncoder().encodeToString(byteArr);
} catch (Exception e) {
//handle
return null;
}
}

The result should be image: "...base64 of the image file...".
byte[] aByteArray = company.getLogo();
String image = Base64.getEncoder().encodeToString(aByteArray);
notification.put("image", image);
For json of course no image needs to be loaded. The blob should contain the bytes of the image (file).

Related

save zoom image level to file

Let's say that I want to load an shp file, do my stuff on it and save the map as an image.
In order to save an image I am using:
public void saveImage(final MapContent map, final String file, final int imageWidth) {
GTRenderer renderer = new StreamingRenderer();
renderer.setMapContent(map);
Rectangle imageBounds = null;
ReferencedEnvelope mapBounds = null;
try {
mapBounds = map.getMaxBounds();
double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0);
imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth));
} catch (Exception e) {
// Failed to access map layers
throw new RuntimeException(e);
}
BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB);
Graphics2D gr = image.createGraphics();
gr.setPaint(Color.WHITE);
gr.fill(imageBounds);
try {
renderer.paint(gr, imageBounds, mapBounds);
File fileToSave = new File(file);
ImageIO.write(image, "png", fileToSave);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
But, let's say I am doing something like this:
...
MapContent map = new MapContent();
map.setTitle("TEST");
map.addLayer(layer);
map.addLayer(shpLayer);
// zoom into the line
MapViewport viewport = new MapViewport(featureCollection.getBounds());
map.setViewport(viewport);
saveImage(map, "/tmp/img.png", 800);
1) The problem is that the zoom level isn't saved on the image file.Is there a way to save it?
2) When I am doing MapViewport(featureCollection.getBounds()); is there a way to extend a little bit the boundaries in order to have a better visual representation?
...
The reason that you aren't saving the map at the current zoom level is that in your saveImage method you have the line:
mapBounds = map.getMaxBounds();
which always uses the full extent of the map, you can change this to
mapBounds = map.getViewport().getBounds();
You can expand a bounding box by something like:
ReferencedEnvelope bounds = featureCollection.getBounds();
double delta = bounds.getWidth()/20.0; //5% on each side
bounds.expandBy(delta );
MapViewport viewport = new MapViewport(bounds);
map.setViewport(viewport );
A quicker (and easier) way to save a map from the GUI is to use a method like this which just saves exactly what is on the screen:
public void drawMapToImage(File outputFile, String outputType,
JMapPane mapPane) {
ImageOutputStream outputImageFile = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(outputFile);
outputImageFile = ImageIO.createImageOutputStream(fileOutputStream);
RenderedImage bufferedImage = mapPane.getBaseImage();
ImageIO.write(bufferedImage, outputType, outputImageFile);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (outputImageFile != null) {
outputImageFile.flush();
outputImageFile.close();
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {// don't care now
}
}
}

Load Canvas image into Excel

I created a plot on Canvas. Now I want to add the image to an Excel file.
I know how to get a WritableImage from Canvas and I know that I need an InputStream to write an image in Excel with addPicture(). The problem is how to link these two.
I could save this image to file and then open and load it to Excel, but maybe there is a way to avoid this?
You could use a PipedInputStream/PipedOutputStream to accomplish this:
Image image = ...
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
PipedOutputStream pos;
try (PipedInputStream pis = new PipedInputStream()) {
pos = new PipedOutputStream(pis);
new Thread(() -> {
try {
ImageIO.write(bImage, "png", pos);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}).start();
workbook.addPicture(pis, Workbook.PICTURE_TYPE_PNG);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
or you could write the data to a array using ByteArrayOutputStream:
Image image = ...
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(bImage, "png", bos);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
workbook.addPicture(bos.toByteArray(), Workbook.PICTURE_TYPE_PNG);

Star micronics receipt printer image from database

I have a sm-t300i and im trying to figure out how to print a image from a database. I have the image data but not sure how to plug it in. I have successfuly added a image from the assets but not sure how to from raw image data. Code below is from assets. Also for some reason the image in the code below will not center is there something else i need to do to center the image. Thank you.
AssetManager assetManager = mContext.getAssets();
InputStream istr = null;
try {
istr = assetManager.open("www/img/logo.bmp");
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(istr);
StarBitmap starbitmap = new StarBitmap(bm, false, 200);
commands.add(new byte[] { 0x1b, 0x61, 0x01 }); //align center
commands.add(starbitmap.getImageEscPosDataForPrinting(false,false));
Looks like you can just convert the base64 and make it a bitmap
String imagex = "iVBORw0KGgoAAAANS etc";
Bitmap bm = StringToBitMap(imagex);
StarBitmap starbitmap = new StarBitmap(bm, true, 600);
commands.add(starbitmap.getImageEscPosDataForPrinting(false,true));
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}

Java java.net.MalformedURLException: no protocol Save Image File from URL

I'm looking to save an image from a website URL that ends in a .jpg extension. Here is the code I'm using:
private void saveImage(String imageURL){
Image img = null;
imageURL = imageURL.substring(2);
try {
URL url = new URL(imageURL);
img = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
try {
ImageIO.write(bimage, "jpg", new File(System.getProperty("user.home") + "/Desktop/image.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
An example URL is this: i.imgur.com/fq4ZpIEb.jpg.
But, everytime I run this code it returns this error message:
java.net.MalformedURLException: no protocol: i.imgur.com/fq4ZpIEb.jpg
Does anyone know a solution? Thanks!
java.net.MalformedURLException: no protocol: i.imgur.com/fq4ZpIEb.jpg
You need the "http://"
ie: "http://i.imgur.com/fq4ZpIEb.jpg" would be the URL.
You have to specify the protocol say http, https or ftp in the image URL

Android taking a screenshot - partial black Google map

Sometimes it works, sometimes it doesn't. I am sharing this picture on Facebook, and sometimes it is ok:
And sometimes it is partial black (only the Google map!):
I have a separate thread doing this screenshot:
new Thread() {
#Override
public void run() {
// Get root view
View view = mapView.getRootView();
view.setDrawingCacheEnabled(true);
// Create the bitmap to use to draw the screenshot
final Bitmap bitmap = Bitmap.createBitmap(
getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_4444);
final Canvas canvas = new Canvas(bitmap);
// Get current theme to know which background to use
final Theme theme = activity.getTheme();
final TypedArray ta = theme
.obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
final int res = ta.getResourceId(0, 0);
final Drawable background = activity.getResources().getDrawable(res);
// Draw background
background.draw(canvas);
// Draw views
view.draw(canvas);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
Bundle params = new Bundle();
params.putByteArray("source", b);
params.putString("message", "genie in a bottle");
try {
//String resp =
facebook.request("me/photos", params, "POST");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}.start();
You can create the Bitmap object directly from the screen using:
bitmap = Bitmap.createBitmap(view.getDrawingCache());
Regards.

Categories