I have very little experience with C#/Asp.net/Razor HTML. I'm trying to change the webcam feature on a web app from using the old jQuery webcam (with flash) project to the jhuckaby/webcamjs (on Github) project. I think the problem right now is that the base64 image isn't saving right. I see in the below code something about String_To_Bytes2. What exactly does that do and do you have any ideas on how I could adjust it to take the input base64 image data from the JavaScript side to be saved in a directory folder?
C#:
public ActionResult Capture(int id)
{
var uniqueFileName = id + ".png";
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "images/photos/");
var path = Path.Combine(uploads, uniqueFileName);
var stream = Request.Body;
string dump;
using (var reader = new StreamReader(stream))
dump = reader.ReadToEnd();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump));
}
else System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump));
return RedirectToAction("ServiceHistory", new { Id = id });
}
private byte[] String_To_Bytes2(string strInput)
{
int numBytes = (strInput.Length) / 2;
byte[] bytes = new byte[numBytes];
for (int x = 0; x < numBytes; ++x)
{
bytes[x] = Convert.ToByte(strInput.Substring(x * 2, 2), 16);
}
return bytes;
}
JavaScript (with a bit of Razor HTML)
<script>
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
//enable_flash: false,
jpeg_quality: 80
});
Webcam.attach('#Camera');
</script>
<script>
function configure() {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
//enable_flash: false,
jpeg_quality: 80
});
Webcam.attach('#Camera');
}
// preload shutter audio clip
var shutter = new Audio();
shutter.autoplay = false;
shutter.src = navigator.userAgent.match(/Firefox/) ? '#Url.Content("~/shutter.ogg")' : '#Url.Content("~/shutter.mp3")';
function take_snapshot() {
// play sound effect
shutter.play();
// take snapshot and get image data
Webcam.snap(function (data_uri) {
// display results in page
document.querySelector('#Camera').innerHTML =
'<img id="imageprev" src="' + data_uri + '"/>';
});
//Webcam.reset();
}
function saveSnap() {
// Get base64 value from <img id='imageprev'> source
var base64image = document.getElementById("imageprev").src;
Webcam.upload(base64image, '#Url.Action("Capture", "Guest", new { Id = #Model.Id })', function (code, text) {
console.log('Save successfully');
console.log('The server responded with a' +' '+ code);
// document.querySelector('#save-btn').style.border = "4px solid green";
configure();
});
}
</script>
Any ideas or explanation would be greatly appreciated. I'm a noob and I feel like I'm so close to getting it to work.
So far, I've tested and I can send the base64 image data to console with console.log and it does indeed generate the image.
It also saves a PNG file in the folder directory, but it's 0kb so something isn't right on the C# side I think.
Again, any assistance would be amazing! Let me know if you need more information.
Related
How to upload Image from local storage to phaser using rest apis ?
It depends what you mean exactly, do you want to upload the image to the server, where the phaser application is running, or should everything be kept locally?
if you only need a local version, you could do this:
load the image
save it in the localStorage of the browser (doesn't work on stackoverflow, code snipplets) : localStorage.setItem('profile', <image-data> )
display the image (or from the localStorage, if it was saved localStorage.getItem('profile', <image-data> ))
if you need it to be uploaded to the server, the answer is a bit more complex and depends on the programming language on the server. But here is a pointer, for the client side: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file
Here a short demo/proof-of-concept:
(without localStorage, since it doesn't work here)
document.body.style = 'margin:0;';
var currentScene;
var profileImage;
var config = {
type: Phaser.AUTO,
width: 536,
height: 173,
scene: { create },
banner: false
};
function create () {
let message = this.add.text(10,10, 'Select a Image');
currentScene = this;
}
new Phaser.Game(config);
let imgElement = document.querySelector('#localImage');
imgElement.addEventListener('change', _ => {
const [file] = imgElement.files
if (file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.onload = _ => {
let txt = currentScene
.textures
.createCanvas('profile', img.width, img.height);
txt.draw(0, 0, img);
profileImage = currentScene.add
.image(20, 40, 'profile')
.setOrigin(0);
profileImage.setScale(180 / img.height);
}
img.src = reader.result;
}
reader.readAsDataURL(file);
}
})
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
<input accept="image/*" type='file' id="localImage" />
i write a code for scan passport id .. i have plustek reader (x50). i can capture image from my device in javascript (webcam.js).. but when capture image the light source not run . how can run the led light before capture image ... i need cod in javascript becouse the device in client side .. my application not mobile apps.. it web application .
// Configure a few settings and attach camera
function configure() {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90,
flip_horiz: true,
});
Webcam.attach('#my_camera');
}
// A button for taking snaps
// preload shutter audio clip
var shutter = new Audio();
//shutter.autoplay = true;
shutter.src = navigator.userAgent.match(/Firefox/) ? 'shutter.ogg' : 'shutter.mp3';
function take_snapshot() {
// play sound effect
shutter.play();
// take snapshot and get image data
Webcam.snap(function (data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<img id="imageprev" src="' + data_uri + '"/>';
////////////
////////////////
var base64image = document.getElementById("imageprev").src;
var strImage = base64image.replace(/^data:image\/[a-z]+;base64,/, "");
//
// $("#<%=Image1.ClientID%>")
// .attr("src", base64image)
});
Webcam.reset();
}
I am using this answer to display the uploaded image in an img tag and also I am able to change the orientation of the image using the loadImage() mentioned in the answer.
My problem is that I am not able to replace the re-oriented image with the uploaded image in the input tag.
The image is not saved unless the form is submitted. So I am not able to do this in AJAX also. Any help is much appreciated.
$('img#image-pre').click(function(e) {
var loadingImage = loadImage($('input#uploadform-file')[0].files[0], function(img) {
var dataURI = img.toDataURL();
document.getElementById("image-pre").src = img.toDataURL();
$('input#uploadform-file')[0].files[0] = function(dataURI) { // create the new blob from the changed image.
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {
type: mimeString
});
};
}, {
orientation: or,
maxWidth: 500,
maxHeight: 300,
minWidth: 100,
minHeight: 50,
});
or = or <= 8 ? or + 1 : 1;
console.log($('input#uploadform-file')[0].files[0]);
});
You may want to look at this:
https://stackoverflow.com/a/20285053/1990724
You can parse the image to base64 string and then using ajax you could post the base64 string to the server. This could be done after you had the user orientate the image the correct way.
I'd like to convert dynamic HTML elements to images (jpg, png, ..) , I don't want to get a screenshot of a webpage nor from a static html file.
The purpose is something like this but on the server-side:
var imgs=[]
for (var i = 0; i < templates.length; i++){
var tempHtml = $(templates[i]).find("#imagePlaceHolder").attr("src", url[i]);
imgs.push(convert2Image(tempHTML));
}
You can use a headless browser PhantomJS and PhantomJS bridge in order to integrate into your application.
A bridge between node and PhantomJS.(https://www.npmjs.com/package/phridge)
var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = {
width: 1920,
height: 1080
};
page.open('http://youwebsite/yourpage', function (status) {
var base64 = page.renderBase64('PNG');
phantom.exit();
console.log(base64);
});
I have developed one game, it has more images so I am thinking load images from server for every game level complete in my phonegap game.
I need to download the images from server to this location
file:///android_asset/www/img in phonegap game.
how can I achieve this?
I have gone through the tutorial Code for displaying image in phonegap
but here they have displayed images on the screen, I dont to save them in img folder..
function storeIntelligrapeLogo() {
//alert('start of file download');
var url = "http://androidexample.com/media/webservice/LazyListView_images/image0.png"; // image url
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
//alert('inside request file sysytem')
// fs.root.getDirectory(myFolderName, {create:true, exclusive:false}, function (folder){});
var imagePath = 'file:///storage/sdcard0'+fs.root.fullPath + "/logo2.png"; // full file path
// var imagePath = 'file:///android_asset/www/'+fs.root.fullPath + "logo2.png";
// alert('inside request file sysytem path fs.root==' + fs.root);
// alert('inside request file sysytem path fs.root.fullPath==' + fs.root.fullPath);
var fileTransfer = new FileTransfer();
fileTransfer.download(url, imagePath, function(entry) {
// alert(entry.fullPath); // entry is fileEntry object
var dwnldImg = document.getElementById("dwnldImg");
dwnldImg.src = imagePath;
dwnldImg.style.visibility = "visible";
dwnldImg.style.display = "block";
}, function(error) {
alert("Some error" + JSON.stringify(error));
});
}) }
I have tried this example but its storing image in the phone memeory but I need to store images into phonegap img folder
Thanks in advance
Use this code :
/**
* Load an image from internet and save it under the default repertory of the application
*/
public void downloadImageFromInternet(String url, String name)
{
ImageLoader.getInstance().loadImage(url,
new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
OutputStream fOut;
// You need to reference your context here. Depending on the class you inherite, "this", "getContext()" or "getActivity()" could work
File file = new File(context.getFilesDir(), name + ".jpeg");
try
{
fOut = new FileOutputStream(file);
loadedImage.compress(Bitmap.CompressFormat.JPEG, 90, fOut);
fOut.flush();
fOut.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
Read the File documentation to understand how to set the path of the saved file. In this code, the file will be saved inside the default folder of your application.
The library you need to download images from the web is Universal Image Loader.