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

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

Related

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

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).

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;
}
}

How to rescale and save an BufferedImage

I got a BufferedImage and want to rescale it before saving it as an jpg/png.
I got the following code:
private BufferedImage rescaleTo(BufferedImage img,int minWidth,int minHeight) {
BufferedImage buf = toBufferedImage(img.getScaledInstance(minWidth, minHeight, Image.SCALE_DEFAULT));
BufferedImage ret = new BufferedImage(buf.getWidth(null),buf.getHeight(null),BufferedImage.TYPE_INT_ARGB);
return ret;
}
public BufferedImage toBufferedImage(Image img) {
BufferedImage ret = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = ret.createGraphics();
g2.drawImage(img,0,0,null);
return ret;
}
public String saveTo(BufferedImage image,String URI) throws UtilityException {
try {
if(image == null)
System.out.println("dododod");
ImageIO.write(image, _type, new File(URI));
} catch (IOException e) {
throw new UtilityException(e.getLocalizedMessage());
}
return URI;
}
But as an result I just get a black picture. It must have to do with the rescaling as when I skip it I can save the expected picture.
As a test, set _type="png" and also use file extension .png when you make the call to ImageIO.write(image, _type, new File(URI));. I had issues like you describe and I started writing type PNG and all works fine. Unfortunately, I never went back to debug why I could not write type JPG, GIF etc.

How do I properly load a BufferedImage in java?

Okay, so I've been trying to load a BufferedImage using this code:
URL url = this.getClass().getResource("test.png");
BufferedImage img = (BufferedImage) Toolkit.getDefaultToolkit().getImage(url);
This gives me a type cast error when I run it though, so how do I properly load a BufferedImage?
Use ImageIO.read() instead:
BufferedImage img = ImageIO.read(url);
BufferedImage img = null;
try {
img = ImageIO.read(new File("D:\\work\\files\\logo.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories