JavaScript sending base64 image string to servlet - javascript

my html code for selecting image and by clicking browserbutton,
<input id="image_file" type="file" class="frmitm" onChange="fileSelected();">
here for selcted code preview showing,
<img id="preview" width="50px" height="50px" border="1" />
here javascript code for selected image & preview showing on page but when i alert or storing in the key its not getting full of string.
function selectedImage(){
var oFile = document.getElementById('image_file').files[0];
var oImage = document.getElementById('preview');
var oReader = new FileReader();
oReader.onload = function(e){
oImage.src = e.target.result;
var resultStr = oImage.src;
var result = resultStr.split(",");
$('#ImageKey').val(result[1]);
};
oReader.readAsDataURL(oFile);
}
here alert($('#ImageKey').val()) i got only half string only like,
/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/+ESC.....etc,
how to get full length of string value.or any other way to convert image to base64 string..
if i saved server response base64 string in var tempImgStr = response.ImgStr;("/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/+ESC..etc")
then alert(tempImgStr), i will get half of string value only.
any suggestions please..

Related

Convert hexadecimal string to Blob and display PNG image with AngularJS

I got a web page (I/m using angularjs 1.4.8) and I'm trying to show an image which comes from my GET url request.
Here is the page code (I got a grid and I/m displaying previews if they are applicable):
<div ng-show="message.message == null && message.is_image != null">
<a href="#" ng-click="downloadFile(message.id_message)">
<img data-ng-src="data:image/{{message.image_resolution}};base64,{{message.image_preview}}"/>
</a>
</div>
So, I got cassandra DB with this blob field and my Json looks like:
created_date:"2017-03-31 22:05:42.284Z"
id_message:"e6e2a5cb-ec25-472f-a59b-3f16a3a8afa9"
id_user_link:"47ed65bf-5520-4901-88c8-01980ffbcd4d"
id_user_sent:"3495c2de-c93c-4323-8e48-1fcecbfde625"
image_length:174443
image_name:"5.png"
image_preview:"0x89504e470d0a1a0a0000000d49484452000007800000039a080600000079a04f28000038714944415478daecd9496e55570045d13bfff124d442c654016320c4d4219832046308a132087199c26ba4f1fed65ad29ec0e99e71ec97635392244992244992244992b4f90d23489224499
...
... some other 90 lines of symbols
...
00000108401d8006c0096244906600000000008c2006c0036004b922403300000000004610036001b802549920118000000008230001b800dc09224c9000c000000004118800dc00660499264000600000080200cc0066003b024493200030000004010066003b001589224198001000000200803b001d8002c49920cc000000000108401d8006c0096244906600000000008c2006c0036004b92a4ff95fe0ffc7d46dd1b63a2b10000000049454e44ae426082"
image_resolution:"png"
is_image:1
message:null
But I have no images in my web page (only icon of broken link to image):
I researched
Angularjs showing image blob
Display blob image in html with angularjs
AngularJS - Show byte array content as image
but this won't help.I tried some varieties of this code:
page:
<img data-ng-src="data:image/{{message.image_resolution}};base64,{{b64encoded(message.image_preview)}}"/>
js:
$scope.b64encoded = function(image_preview){
//btoa(String.fromCharCode.apply(null, response.data[0].ClassImage.data));
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image_preview\//);
return btoa(String.fromCharCode.apply(null, image_preview));
}
RESOLVED
Finally, that was not the issue about AngularJS or blob - that was a Java issue:
byte[] previewSizeByte = baos.toByteArray(); and I stored this one as blob, so, now I got a text field and my Java code looks like (I decided to use BufferedImage for preview):
String base64String = imgToBase64String(preview, fileFormat);
and
private String imgToBase64String(BufferedImage preview, String fileFormat) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(preview, fileFormat, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
I really appreciate stackoverflow members for their comments and answers, they were extremely helpful
It appears that the CassandraDB is sending the image data as a hexadecimal string. It would be more efficient to send it as a base64 string and it would be easier to use.
Here is a function to convert a hexadecimal string to an image/png Blob and display the image:
angular.module("myApp",[]).controller("myVm", function($scope) {
var vm = $scope;
var testHex =
["0x89504e470d0a1a0a0000000d494844520000003c00000028040300000050",
"9584cc0000001b504c5445000000ffffff1f1f1f7f7f7f3f3f3f9f9f9f5f",
"5f5fdfdfdfbfbfbf2cb790f6000000097048597300000ec400000ec40195",
"2b0e1b000000b749444154388ded90cf0a83300cc63faaf5394a5defc56c",
"ee2a0c760e2a3b0b6e3ec7c0175f5aff1e77da657ea40dcd2ff90a010efd",
"9772a2f3f6ea4b830e121915b1a04e859999066a4b1801562dec544c3d36",
"cc723506ac9791809538f564af54055c33f8861d76d0cacfd30efc9450c3",
"b0e20189e28847aac5397458b7e2175d4cde4ed37252cff7d83ce367c849",
"b56014ecf638fa28bf62cd49b7c3e9a384f86764269cbde5bf665b969230",
"31adb25feffdd02ff50109f91bbd7897f34a0000000049454e44ae426082"]
.join('');
vm.hex = testHex;
vm.imgUrl = URL.createObjectURL(toPngBlob(testHex));
function toPngBlob(str){
var hexStr = str.slice(2);
var buf = new ArrayBuffer(hexStr.length/2);
var byteBuf = new Uint8Array(buf);
for (let i=0; i<hexStr.length; i+=2) {
byteBuf[i/2] = parseInt(hexStr.slice(i,i+2),16);
}
var blob = new Blob([byteBuf], {type: "image/png"});
return blob;
};
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myApp" ng-controller="myVm">
<h1>Convert hex string to PNG Blob</h1>
{{hex}}<br>
{{imgUrl}}<br>
<img ng-src="{{imgUrl}}">
</body>

Add Dynamic Variable in URL Content in JQuery

I am trying to add attach my variable on my script section, since my filename is in GUID format. The filename is in hidden field:
string strDirectory = Server.MapPath(Url.Content("~/Content/AnnouncementImages/"));
string[] strFiles = Directory.GetFiles(strDirectory);
string strFileName = string.Empty;
foreach (var strFile in strFiles)
{
strFileName = Path.GetFileName(strFile);
}
<img id="myImg" src="#Url.Content("~/Content/AnnouncementImages/" + strFileName)" width="300" height="200" />
<input type="hidden" id="hiddenStringFileName" value="#strFileName"/>
In script section, I am trying to get this hidden field value:
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName');
//This is not working so far since it says cannot resolve symbol filename on below code:
modalImg.src = '#Url.Content("~/Content/AnnouncementImages/" + filename);
}
I am not sure what you are trying to do but if you want razor code plus javascript, you can put it in your view. Obviously this will no longer be unobtrusive javascript. But to do what you want, this will work. I added a button when you click it, it calls the function to show the concatenated URL.
#{
ViewBag.Title = "Test";
var strFileName = Guid.NewGuid();
}
<input type="hidden" id="hiddenStringFileName" value="#strFileName" />
<button onclick="fncAnnouncementLoad()">Show</button>
<script>
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName').value;
//This is not working so far since it says cannot resolve symbol filename on below code:
var src = '#Url.Content("~/Content/AnnouncementImages/")' + filename;
alert(src);
}
</script>

convert to base64 and send image using ajax in Javascript

I need to send selected image to the server, here is already I have tried
here is HTML part
<div class="row">
<input type="file" name="filUpload" id="filUpload" onchange="showimagepreview(this)">
<br />
<img id="imgprvw" alt="uploaded image preview" class="img-thumbnail" />
</div>
I need to get encoded image into javascript variable,But I have no idea
for uploading image on to server you need to send image data via AJAX to server side.
for reference you can see this link :
http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php
http://phppot.com/php/php-ajax-image-upload/
you can try using jquery's base64 plugin. Jquery.Base64 plugin
and do it like this:
function showimagepreview(c) {
var file = c;
if(file.files.length)
{
var reader = new FileReader();
reader.onload = function(e)
{
var b = $.base64.encode(e.target.result);
$("#imgprvw").attr("src", "data:image/png;base64," + b);
};
reader.readAsBinaryString(file.files[0]);
}
}

Passing image data to another page

I'm trying to access a camera and a photo album on a mobile device and get the chosen image. I did that with the code below. My problem is, it generates image data, and I have to transfer that to another page, but because of the size of the generated string, I can't use URL parameters. It shows me the error: [404] Request-URI Too long. How can I pass the information to the other page?
Here is the code: http://jsfiddle.net/8u426/
The JS:
<script>
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
document.getElementById("fotoImg").src = oFREvent.target.result;
document.getElementById("fotoImg").style.visibility = "visible";
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
document.getElementById("fotoImg").style.height = screenHeight;
document.getElementById("stringImg").innerText = "Data Image: " + oFREvent.target.result;
};
$(function() {
$("input:file").change(function (){
var input = document.querySelector('input[type=file]');
var oFile = input.files[0];
oFReader.readAsDataURL(oFile);
});
});
</script>
Update:
The problem is: if I try to open a new page passing the Data Image string as a parameter in the URL (with "?"). The new page will show the 404 error that I mentioned, because the string is too long.
Try changing your form to
<form id="form1" method="POST" action="[Page2 URL]">
<input id="filePic" type="file" name="image" accept="image/*" capture />
</form>
where [Page2 URL] is the URL for page to receive the image uploaded.
And JavaScript to
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
var img = $('#fotoImg');
img.attr('src', oFREvent.target.result);
img.css( { height : screenHeight, visibility: 'visible' });
$("#stringImg").text( "Data Image: " + oFREvent.target.result);
$('#form1').submit();
};
$(function() {
$("input:file").change(function (){
var oFile = this.files[0];
oFReader.readAsDataURL(oFile);
});
});
I couldn't make work with php (considering that I didn't want to work with php) and html forms (methods get and post)... So I used the jQuery library called "jQuery Storage".
It was easy, on the page that I select the image you shoud use:
$.sessionStorage([key],[value]);
So, was like that:
$.sessionStorage('chosenImg', document.getElementById("photoImg").src);
And in the new page, to get the value, just add in the code:
$.sessionStorage('chosenImg');
Of course, I had to download de .js library from the website and add the line below on both html pages:
<script src="jquery.storage.js"></script>
The only inconvenient it is a little heavy for mobile, but was the only way I found...
That is it! Thanks everyone!
dataimage base64 data image

How to get base64 encoded data from html image

I have a registration form where users can choose an avatar. They have 2 possibilities:
Choose a default avatar
Upload their own avatar
In my HTML page I have this.
<img id="preview" src="img/default_1.png">
It displays the chosen avatar.
I use the File Api to let users upload their own image.
That makes the src of the HTML image to something like this.
<img id="preview" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA... />
When they post the registration form. The data will be sent to a REST service.
I can send the base64 encoded data when a user uploaded an avatar himself. But how do I handle the default avatar? It is an url instead of base64 encoded data.
You can try following sample
http://jsfiddle.net/xKJB8/3/
<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );

Categories