How To Calculate the DPI of Buffered Image using Java - java

Firstly, I have to convert the image into Base64 and then calculate the DPI of an image by converting base64 to buffered Image.
Here is some code that I tried and that works well for image.PNG(.png) format but return -1(wrong output) in other formats like(.jpg)...!
But I need this to also work for other formats too.
private static float base64toBuffer(String inputbuffer) throws IOException, ImageReadException{
byte[] Rimage=decodeToImage(inputbuffer);
final org.apache.sanselan.ImageInfo imageInfo = Sanselan.getImageInfo(Rimage);
final int physicalWidthDpi = imageInfo.getPhysicalWidthDpi();
final int physicalHeightDpi = imageInfo.getPhysicalHeightDpi();
return physicalWidthDpi;
}
private static byte[] buffertoByte(String imageString) {
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
return imageByte;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Related

How can I encrypt a BufferedImage to only be read by the program?

I have this method here in a class named Buffers:
private static BufferedImage load(String s){
BufferedImage image;
try{
image = ImageIO.read(Buffers.class.getResourceAsStream(s));
return image;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
That all the graphic contents in the project uses to load up the images. Example:
public static BufferedImage background = load("/path/");
I want to know if there is a way to only load encrypted images and then be decrypted only when called by this method.
If there is any doubt about what I'm trying to ask, please let me know.
Thank you!
A way to have encrypted file is to use CipherInputStream and CipherOutputStream:
private BufferedImage load(String s){
BufferedImage image;
try{
image = ImageIO.read(getDecryptedStream(Buffers.class.getResourceAsStream(s)));
return image;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
private InputStream getDecryptedStream(InputStream inputStream) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, this.key);
CipherInputStream input = new CipherInputStream(inputStream, cipher);
return input;
}
Use the outputStream to save the file
private OutputStream getEncryptedStream(OutputStream ouputStream) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, this.key);
CipherOutputStream output = new CipherOutputStream(ouputStream, cipher);
return output;
}

Send an Image from c# server to Android client. Decoding issue

I want to send an image Bitmap from a c# server to an App in Android Java and I'm having a problem by decoding the file in java.
Te code in c# to decode an image into a string is as follows:
String bildString = ImageToString("C:\\Users\\Public\\Pictures\\Penguins.jpg");
public static string ImageToString(string path){
if (path == null)
throw new ArgumentNullException("path");
System.Drawing.Image im = System.Drawing.Image.FromFile(path);
MemoryStream ms = new MemoryStream();
im.Save(ms, im.RawFormat);
byte[] array = ms.ToArray();
return Convert.ToBase64String(array);
}
The string is transferred; and here comes the error in Java when I want to recover my image:
Bitmap bildAM = StringToBitMap(bildString);
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;
}
I receive following Exception:
StackTrace

How to get Base64 String from InputStream?

I'm on a problem by taking the selected gallery picture and want to save it first as Base64 String in a XML file (for later use. For example if you exit the app and open it again).
As you can see I get the Image on a InputStream
But first of all the onClick method:
public void onClick(DialogInterface dialog, int which) {
pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT);
pictureActionIntent.setType("image/*");
startActivityForResult(pictureActionIntent,GALLERY_PICTURE);
}
Now in the onActivityResult method I want to store the image from InputStream to Base64 String.
case GALLERY_PICTURE:
if (resultCode == RESULT_OK && null != data) {
InputStream inputstream = null;
try {
inputstream = getApplicationContext().getContentResolver().openInputStream(data.getData());
Base64InputStream in = new Base64InputStream(inputstream,0);
} catch (IOException e) {
e.printStackTrace();
}
#EDIT
This is what I do after creating the base64 String.
Bitmap bmp = base64EncodeDecode.decodeBase64(Items.get("image"));
Image1.setImageBitmap(bmp);
And this is the decoding Method:
public Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
I tried to use Base64InputStream but without success.
Can you give me a hint how to get from InputStream to Base64 String?
How many steps it will take doesn't matter.
I hope someone can help me!
Kind Regards!
Write these lines in onActivityResult method
try {
// get uri from Intent
Uri uri = data.getData();
// get bitmap from uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// store bitmap to file
File filename = new File(Environment.getExternalStorageDirectory(), "imageName.jpg");
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, out);
out.flush();
out.close();
// get base64 string from file
String base64 = getStringImage(filename);
// use base64 for your next step.
} catch (IOException e) {
e.printStackTrace();
}
private String getStringImage(File file){
try {
FileInputStream fin = new FileInputStream(file);
byte[] imageBytes = new byte[(int)file.length()];
fin.read(imageBytes, 0, imageBytes.length);
fin.close();
return Base64.encodeToString(imageBytes, Base64.DEFAULT);
} catch (Exception ex) {
Log.e(tag, Log.getStackTraceString(ex));
toast("Image Size is Too High to upload.");
}
return null;
}
you can use base64 String of image.
Also don't forget to add permissions in AndroidManifest.xml file READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE
EDIT:: Decode base64 to bitmap
byte[] bytes = Base64.decode(base64.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView) this.findViewById(R.id.ImageView);
image.setImageBitmap(
BitmapFactory.decodeByteArray(bytes, 0, bytes.length)
);
Hope it'll work.
This should work:
public static byte[] getBytes(Bitmap bitmap) {
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
stream.flush();
//bitmap.compress(CompressFormat.PNG, 98, stream);
bitmap.compress(CompressFormat.JPEG, 98, stream);
//bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
return stream.toByteArray();
} catch (Exception e){
return new byte[0];
}
}
public static String getString(Bitmap bitmap){
byte [] ba = getBytes(bitmap);
String ba1= android.util.Base64.encodeToString(ba, android.util.Base64.DEFAULT);
return ba1;
}
Got this code from something I use in an application, stripped it down to the most basic as far as i know.
If you are selecting image from Gallery then why you are saving it as Base64 string in xml file , you can reuse that image from gallery .
For this save image url in SharedPreferences and use that url again to show image .
Edit :
If you want to store it locally then you can use SQLite Database to store it , for more detail visit this link .

How to serialize and deserialize a RenderedImage as a text string?

I want to serialize a RenderImage as a text string so that I can java a Jason-like file with some fields (Name, Date, Photo).
I would like to use
String s = String.format("%s:%s,%s:%s,%:%s",
"name", my_name,
"date", date,
"photo", someFunctionToGenerateAStringForTheImage(RenderedImage));
And save s to a file.
Currently, I am using this:
public static byte[] imageToByteArray(RenderedImage img) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
ImageIO.write(img, "png", out);
out.flush();
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
And I call it as such:
String imageAsString =new String(Util.imageToByteArray(post.getImage()));
I deserialize the strings using the following function:
public static RenderedImage byteArrayToImage(byte[] bytes) {
try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
return ImageIO.read(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Thus I call it as such byteArrayToImage(imageAsString.getBytes());
Unfortunately, this approach is not working, the objects produced aren't the same... I would like to it using a String.format because my code is much more complex and full of recursive calls, so I want the simplest way of achieving this.
What can you recommend me?
You can try using Data URL:
public static String imageToDataUrl(RenderedImage img) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try {
ImageIO.write(img, "png", bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
String data = DatatypeConverter.printBase64Binary(bytes.toByteArray()),
//proper data url format
dataUrl = "data:image/png;base64," + data;
return dataUrl;
}
And to deserialise:
public static RenderedImage dataUrlToImage(String dataUrl) {
String data = dataUrl.substring(dataUrl.indexOf(',')+1);
byte[] bytes = DatatypeConverter.parseBase64Binary(data);
try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
return ImageIO.read(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Create class
class MyImage {
String name;
Date date;
String photo;
}
and use any json lib, for example GSON:
String s = new GSON.toJson(myImage).replace('{'}.replace{'}');
MyImage myImage = new GSON.fromJson("{"+s+"}", MyImage.class);
Update:
if you have problem with serialization image try to use:
String s = new String(utf8Bytes, "UTF8");
byte[] utf8Bytes = original.getBytes("UTF8");
instead of
String s = new String(utf8Bytes);
byte[] defaultBytes = original.getBytes();

BufferedImage into Android bitmap

I've got a problem. I need to save a java BufferedImage object in an String. Convert this String on the Android application into Bitmap. How can I achieve this? Or maybe you can recommend me the other way to transfer image information in the String format.
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
imageString = Base64.getEncoder().encodeToString(imageBytes);
bos.close();
} catch (IOException e) {
log.error("Can't encode to String");
}
return imageString;
}
Base64 encoding and decoding of images using Java 8:
public static String imgToBase64String(final RenderedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
public static BufferedImage base64StringToImg(final String base64String) {
try {
return ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64String)));
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
hope so will work,
enjoy your code:)

Categories

Resources