Image Orientation - java

I have been researching this for a long time.
I need to know how to get an image's orientation by reading it from the metadata tags.
I have looked at Exif, and other 3rd party code. I'am just interested to learn how to do it just from the reading the metadata tags.
I had a code that reads the IIOMetadata but the image dimension tag or orientation will just say normal.
Any suggestions?

https://github.com/exif-js/exif-js/blob/master/exif.js
function base64ToArrayBuffer (base64) {
base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
var binaryString = atob(base64);
var len = binaryString.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(e.target.result));
console.log(exif.Orientation, exif.Make);

Related

AWS lambda (server less) file upload using java

I'm trying to upload file to AWS S3 bucket using Lambda server less application written in Java.
I'm hitting the endpoint with file using postman option binary (screenshot attached).
And I'm receiving binary content as string in my endpoint like as follows (screenshot attached).
I'm trying to convert this binary string to byte array and upload to S3 bucket.
I'm getting success response, But when i downloads the file / image it's looks like not an actual file.
Sample code:
#Override
public ServerlessOutput handleRequest(ServerlessInput serverlessInput, Context context) {
ServerlessOutput output = new ServerlessOutput();
String keyName = UUID.randomUUID().toString();
String content = serverlessInput.getBody();
byte[] encoded = this.toBinary(content).getBytes();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(encoded.length);
metadata.setContentType(PNG_MIME);
s3.putObject(new PutObjectRequest(
ARTICLE_BUCKET_NAME,
keyName,
new ByteArrayInputStream(encoded),
metadata)
);
output.setBody("Successfully inserted article ");
}
private String toBinary(String data) {
byte[] bytes = data.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++) {
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
return binary.toString();
}

Difference in Base64 encoding

I am trying to encode, Image to Base 64 string in AngularJS2
handleFileSelect(evt) {
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
_handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
this.model.UserProfileImageBase64 = btoa(binaryString);
console.log(this.model.UserProfileImage);
}
I am receiving a different string,in compare to encoding it from Java
Base64.encodeToString(getBytesFromBitmap(bitmap),Base64.NO_WRAP);
Any Idea how can we match both Base64 encoding? I had tried same with base64 encoding in angular as well
this.model.UserProfileImageBase64 = Base64.encode(binaryString);
But no dfiference in result.
BtoA and Base64 producing same result and, if I am verifying it online I am getting image as well but I need it in the same format which is generated by Java
I am getting the same result with java and javascript.
With java I did:
byte[] imageBytes = IOUtils.toByteArray(new URL("https://www.w3schools.com/css/paris.jpg"));
String base64 = Base64.getEncoder().encodeToString(imageBytes);
System.out.println(base64);
With javascript I did:
const fileReader: FileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = () => {
retVal.next(fileReader.result);
};
NOTE: I would suggest not to use readBynaryAsString as it is deprecated and might not work. FileReader
NOTE: That in javascript I wait till the file is uploaded to get the data and I passed to an observable next(...)
changeListener($event) : void {
this.readThis($event.target);
}
readThis(inputValue: any): void {
var file:File = inputValue.files[0];
var myReader:FileReader = new FileReader();
myReader.onloadend = (e) => {
this.image = myReader.result;
}
myReader.readAsDataURL(file);
}
component.html
<input type="file" accept="image/*" (change)="changeListener($event)">
Follow this link Angular 2 encode image to base64

convert dataURL to file using javascript

In one of my application i am cropping the image using http://fengyuanchen.github.io/cropper/
The resultant cropped image am getting in the base64 dataURL format, but i required that to be in file object format.
How to convert the dataURL to file either in client side or server side.
Use Blob instead of the deprecated BlobBuilder. The code is very clean and simple. (Manuel Di Iorio's code is deprecated.)
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
//test:
//var blob = dataURLtoBlob('data:text/plain;base64,YWFhYWFhYQ==');
Data URI scheme
How to convert dataURL to file object in javascript?
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var bb = new BlobBuilder();
bb.append(ab);
return bb.getBlob(mimeString);
}
Then just append the blob to a new FormData object and post it to your server using ajax:
var blob = dataURItoBlob(someDataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
fd.append("myFile", blob);
xhr.open('POST', '/', true);
xhr.send(fd);
Thats my validation for input.
$data = $_POST['thumb'];
$uriPhp = 'data://' . substr($data, 5);
if ( base64_encode(base64_decode($uriPhp))){
$_POST['thumb'] = $uriPhp;
}
for saving I am using : http://www.verot.net/php_class_upload.htm
$foo = new Upload($_POST['thumb']);
if ($foo->uploaded) {
// save uploaded image with a new name
$foo->file_new_name_body = $name;
$foo->image_convert = 'png';
$foo->Process("uploads/");
}

Invalid value for ByteString for Update photo in Google Apps engine in java

I am trying to update photo using Google apps engine.I have imageurl i convert it into byte array and then encode
it using base64.i got encoded string,now i m trying to update photodata using directory API Reference
https://developers.google.com/admin-sdk/directory/v1/reference/users/photos#resource
after update i got error invalid byteString.I face this problem from yesterday.So Let me know where i did wrong? Below is my code.
import com.google.appengine.repackaged.org.apache.commons.codec.binary.Base64;
above class used for Base64.
URL url = new URL(myImageUrl);
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
bais.write(byteChunk, 0, n);
}
System.out.println(byteChunk);
byte[] encoded = Base64.encodeBase64(byteChunk);
String ecodedString = new String(encoded, "UTF-8");
ecodedString = ecodedString.replace("/", "_");
ecodedString = ecodedString.replace("+", "-");
ecodedString = ecodedString.replace("=", "*");
System.out.println(ecodedString);
Padding could be the problem, try not replacing "=" with "*". See also:
Converting string to web-safe Base64 format
p.s. repackaged libs are discouraged in app engine; you may use DatatypeConverter.printBase64Binary() instead.

Convert an image to binary data (0s and 1s) in java

I want to read an image from a url and convert it into binary data. Please help me..
byte[] data = null;
ByteArrayOutputStream bas = null;
try {
URL u = new URL(
"http://www.eso.org/public/archives/images/screen/eso0844a.jpg");
HttpURLConnection con1 = (HttpURLConnection) u.openConnection();
con1.setAllowUserInteraction(true);
con1.setRequestMethod("GET");
con1.connect();
InputStream is = con1.getInputStream();
BufferedImage imgToServe = null;
if (is != null) {
imgToServe = ImageIO.read(is);
}
bas = new ByteArrayOutputStream();
ImageIO.write(imgToServe, "jpg", bas);
File f = new File("C:\\img.jpg");
ImageIO.write(imgToServe, "jpg", f);
data = bas.toByteArray();
String str = "";
for (int i = 0; i < data.length; i++) {
str = str + toBinary(data[i]);
}
System.out.println(str);
} catch (HTTPException he) {
} catch (IOException ioe) {
}
}
private static String toBinary(byte b) {
StringBuilder sb = new StringBuilder("00000000");
for (int bit = 0; bit < 8; bit++) {
if (((b >> bit) & 1) > 0) {
sb.setCharAt(7 - bit, '1');
}
}
return (sb.toString());
}
If you're reading the image from a URL, it will already be in a binary format. Just download the data and ignore the fact that it's an image. The code which is involved in download it won't care, after all. Assuming you want to write it to a file or something similar, just open the URLConnection and open the FileOutputStream, and repeatedly read from the input stream from the web, writing the data you've read to the output stream.
If that's not what you were after, please clarify the question.
EDIT: If you really want to get the data as individual bits (which seems somewhat odd to me) you should separate the problem in two:
Downloading the data (see above; if you don't need it on disk, consider writing to a ByteArrayOutputStream)
Converting arbitrary binary data (a byte array or an input stream) into 0s and 1s
How you tackle the latter task will depend on what you actually want to do with the bits. What's the real aim here?
You can use the standard ImageIO for this. The read method takes a URL and retrieves it to an Image. Then you can use the write method to write it to a File or like in this case a ByteArrayOutputStream which outputs the image to a in-memory buffer.
public static void main(String[] args) throws Exception {
// read "any" type of image (in this case a png file)
BufferedImage image = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));
// write it to byte array in-memory (jpg format)
ByteArrayOutputStream b = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", b);
// do whatever with the array...
byte[] jpgByteArray = b.toByteArray();
// convert it to a String with 0s and 1s
StringBuilder sb = new StringBuilder();
for (byte by : jpgByteArray)
sb.append(Integer.toBinaryString(by & 0xFF));
System.out.println(sb.toString());
}
Load the image from path/url into BufferedImage
public static Raster loadImageRaster(String file_path) throws IOException
{
File input = new File(file_path);
BufferedImage buf_image = ImageIO.read(input);
buf_image = binarizeImage(buf_image);
return buf_image.getData(); //return raster
}
Make a Binary Type BufferedImage from the original BufferedImage
public static BufferedImage binarizeImage(BufferedImage img_param)
{
BufferedImage image = new BufferedImage(
img_param.getWidth(),
img_param.getHeight(),
BufferedImage.TYPE_BYTE_BINARY
);
Graphics g = image.getGraphics();
g.drawImage(img_param, 0, 0, null);
g.dispose();
return image;
}
Convert the BufferedImage to Raster so that you can manipulate it pixel by pixel
imageRaster.getSample(x, y, 0)
Raster.getSample(x,y, channel) will return 0s or 1s.
channel = 0 for TYPE_BYTE_BINARY images

Categories

Resources