Upload images with preview on picture box in asp.net mvc - asp.net-mvc

I want to upload image in asp.net mvc like this way.I am using input type file for uploading images , its working fine but I want that when user click on this image and select that image , that image would appear on this type of box , how would I do that . I am saving images path in database and putting them on file directory.

I suspect the best bet is to use the HTML5 file API to read the contents of the attached image to display a preview. When the user submits the file you could do the server-side processing as you currently are, store the URL and return to the browser the location of the new image for proper preview. But check the performance of previewing a large image.
The link shows an example of previewing the file. I've copied the code in here as well, but please check the article for better understanding.
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

Related

How to get HTML5 video thumbnail without using poster on safari or iOS?

I have embedded HTML5 video with mp4 format. How to get thumbnail image like poster without using "poster" attribute. This problem coming on Safari and iOS. I have added video like below mentioned code.
<video height=350 id='TestVideo' webkit-playsinline><source src='test.mp4' type=video/mp4></video>
On Chrome, IE, Firefox first frame of video coming as thumbnail image, but not coming on Safari and iOS.
simply add preload="metadata" in video tag and set #t=0.1 at url src, it will get the frame of 0.1s of your video as thumbnail
however, the disadvantage of this solution is when you click to play the video, it always start at 0.1s
<video preload="metadata" controls>
<source src="video.mp4#t=0.1" type="video/mp4">
</video>
If you want to do this without storing server side images it is possible, though a bit clunky... uses a canvas to record the first frame of the video and then overlay that over the video element. It may be possible to use the URL for the Canvas as a source for the Poster (eg video.poster = c.toDataURL();) but that requires correct CORS setup (not sure if the video was on your own server, and if you have control over that, so took the safest option). This will work best if video is correctly encoded for streaming (so MOOV atom is at the front of the video, otherwise it will be slow to draw the overlay - see this answer for more detail)
The HEAD contains styling for the video and the overlay (you will need to adjust sizing and position to suit your application)
<head>
<style>
video_box{
float:left;
}
#video_overlays {
position:absolute;
float:left;
width:640px;
min-height:264px;
background-color: #000000;
z-index:300000;
}
</style>
</head>
In the BODY you will need the div for the overlay and the video. The overlay div has an onclick handler to hide the overlay and start the video playing
<div id="video_box">
<div id="video_overlays" onclick="this.style.display='none';document.getElementById('video').play()"></div>
<video id="video" controls width="640" height="264">
<source src="BigBuck.mp4" type='video/mp4'>
</video>
</div>
</div>
Finally you will need code that will load the video, seek to the first frame and load the visual into a canvas that you then insert into the overlay
<script>
function generateOverlay() {
video.removeEventListener('seeked',generateOverlay); / tidy up the event handler so it doesn't redraw the overlay every time the user manually seeks the video
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
c.width = 640;
c.height = 264;
ctx.drawImage(video, 0, 0, 640, 264); // take the content of the video frame and place in canvas
overlay.appendChild(c); // insert canvas into the overlay div
}
// identify the video and the overlay
var video = document.getElementById("video");
var overlay = document.getElementById("video_overlays");
// add a handler that when the metadata for the video is loaded it then seeks to the first frame
video.addEventListener('loadeddata', function() {
this.currentTime = 0;
}, false);
// add a handler that when correctly seeked, it generated the overlay
video.addEventListener('seeked', function() {
// now video has seeked and current frames will show
// at the time as we expect
generateOverlay();
}, false);
// load the video, which will trigger the event handlers in turn
video.load();
</script>
this is a bit late but we had the same scenario. I can't use the attribute 'muted' because my videos are podcasts. This is what I came up with and I hope to share it with future visitors. What I did is load the video in the body tag, drew a canvas, retrieved as base64 and applied to the video as the background image.
Since my video should be fixed 150px in height, I computed the aspect ratio so that whatever height and width of the actual video, it will be resized into 150px height and dynamic width.
$('body').append('<video class="checkmeload" style="position:absolute;top:-10000px" controls preload="auto" playsinline src="//src-here"><source src="//src-here" type="//videotype-here"></video>');
$('body').find('.checkmeload').on('loadeddata', function(){
var video = $('.checkmeload');
var canvas = document.createElement('canvas');
aspectratio = (video[0].videoWidth / video[0].videoHeight);
newwidth = (150 * aspectratio);
canvas.width = newwidth;
canvas.height = 150;
var context = canvas.getContext('2d');
context.drawImage(video[0], 0, 0, canvas.width, canvas.height);
var dataURI = canvas.toDataURL('image/jpeg');
$('body').find('.checkmeload').remove();
$('#myvideo').css('background-image','url("'+dataURI +'")');
});
Source: How to set the thumbnail image on HTML5 video?
This worked for me:
<img src="thumbnail.png" alt="thumbnail" />
/* code for the video goes here */
Now using jQuery play the video and hide the image as
$("img").on("click", function() {
$(this).hide();
// play the video now..
})
Add #t=0.001 at the end of the video URL.
https://muffinman.io/blog/hack-for-ios-safari-to-display-html-video-thumbnail/

Titanium Alloy: Saving a View as image to the photoGallery?

So I currently have a window with a view (id="newPhoto") in which I put an image from a previous step. Onto this newPhoto-view I position a new view (id="content") via css with an icon and some text on it.
Then I want to save the parent view with the image and the icon and text on it as a new image to the photoGallery. What would be the easiest way? To put all in one view and save the new view, or to screenshot the desired part and save it?
Cannot make this to work :(
my filterWindow.xml file:
<Alloy>
<Window id="filterWindow">
<View id="finalImage" />
<View id="selectedPhoto" />
<View id="counter">
<ImageView id="weatherIcon" />
<Label id="label" />
</View>
<Button id="filterAndSaveBtn" onClick="filterAndSave">Filter</Button>
</Window>
</Alloy>
My filterWindow.js:
var photo = Alloy.createController('photo').getView();
$.selectedPhoto.add(photo);
$.selectedPhoto.width = appWidth;
$.selectedPhoto.height = appWidth;
$.label.text = "Some text";
function filterAndSave(e) {
var blob = $.finalImage.toBlob();
Ti.Media.saveToPhotoGallery(blob,{
success: function(e){
alert('Saved image to gallery');
},
error: function(e){
alert("Error trying to save the image.");
}
});
}
Thanks in advance for having a look at this one!
I had a similar issues in one of my projects. I made a screenshot of the area I needed as the new picture.
//This should be put in your filterAndSave method
if (Ti.Platform.osname == "android") {
var image = $.imageContainer.toImage().media;
} else {
var image = $.imageContainer.toImage(null, true);
}
//Saving the image if it is needed somewhere else
var f = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, "finalChallengeImage.jpeg");
f.write(image);
//Save it to the gallery and do what has to be done
You should have a look at the official documentation of the toImage() function. It needs different arguments depending on the platform you are using.
Please note that I did not needed to save the image to the gallery so that must be done additionally (although it seems like you already figured out how to do this).
Ok... found it. Need to Save it as a png file, otherwise it sets the background of the overlapping element white though it has a smaller height. But anyway... saving as a png works. But have only tried it in iOS.
So here is the final working code:
filterWindow.xml:
<View id="finalImage">
<View id="selectedPhoto" />
<View id="counter">
<ImageView id="weatherIcon" />
<Label id="label" />
</View>
</View>
filterWindow.js:
var photo = Alloy.createController('photo').getView();
// adding the selected photo from the previous step into the first child-View
$.selectedPhoto.add(photo);
$.selectedPhoto.width = appWidth;
$.selectedPhoto.height = appWidth;
$.finalImage.width = appWidth;
$.finalImage.height = appWidth;
$.label.text = "Some text";
function filterAndSave(e) {
if (Ti.Platform.osname == "android") {
var image = $.finalImage.toImage().media;
} else {
var image = $.finalImage.toImage(null, true);
}
//Saving the image if it is needed somewhere else
var f = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, "finalImage.png");
f.write(image);
//Save it to the gallery
Ti.Media.saveToPhotoGallery(image,{
success: function(e){
alert('Saved image to gallery');
},
error: function(e){
alert("Error trying to save the image.");
}
});
}
Once again, thanks so much for your, Robin.

Responsive Image, Bootstrap 3 and Umbraco 7.2.1

While I'm using Umbraco 7.2.1, I want the image I insert to be responsive (img-responsive) of bootstrap.
How can i do that?
I'm not sure how you are adding the images to your pages but I had this problem when I started using the new grid layout in Umbraco 7.2.
So if you are also using the grid layout what you need to do is open the view "Partial Views\Grid\Editors\Media.cshtml" and add the class there.
...
<img src="#url" class="img-responsive" alt="#Model.value.caption">
...
This will add the class to ALL images added to the grid layout with the standard "Image" grid editor.
You can add your own custom class to to images in
~/umbraco_client/tinymce3/plugins/umbracoimg/img/image.js
Look for where it says tinymce.extend(). It should end up looking something like this:
tinymce.extend(args, {
src: nl.src.value,
width: nl.width.value,
height: nl.height.value,
alt: nl.alt.value,
title: nl.alt.value,
rel: nl.orgWidth.value + ',' + nl.orgHeight.value,
class: 'img-responsive'
});
I've only done this in Umbraco 6, so hopefully the answer is still the same in Umbraco 7.
I don't advise altering anything in the /umbraco/ or /umbraco_client/ folders since any future updates will undo your changes, forcing you to reapply them.
Assuming you want to add a responsive class to images entered in the rich text editor, I would recommend creating a new css rule for img elements that adds the relevant properties from .img-responsive.
For example:
You add a rich text data type called bodyText to a document type in Umbraco. In your template for this document, wrap the rendering call in an element with the class .bodyText.
<div class="bodyText">
#Umbraco.Field("bodyText")
</div>
In your stylesheet, create a new rule for .bodyText img that inherits the properties from the .img-responsive class.
.bodyText img {
max-width: 100%;
height: auto !important;
}
Note !important on the height property. This is added to ensure that the inline-style added for height are overridden. When an editor changes the dimensions of an image in the rich text editor, tinyMCE will add the new dimensions to the image's inline style attribute, thus killing the responsive height.
I did it very easily in Umbraco 7.5.5, change /Umbraco/Js/umbraco.services.js:
$timeout(function () {
var imgElm = editor.dom.get('__mcenew');
var size = editor.dom.getSize(imgElm);
if (editor.settings.maxImageSize && editor.settings.maxImageSize !== 0) {
var newSize = imageHelper.scaleToMaxSize(editor.settings.maxImageSize, size.w, size.h);
// images must be responsive: commented 3 lines of code, added addClass with img-responsive,
// var s = "width: " + newSize.width + "px; height:" + newSize.height + "px;";
// editor.dom.setAttrib(imgElm, 'style', s);
editor.dom.addClass(imgElm, 'img-responsive');
editor.dom.setAttrib(imgElm, 'id', null);
if (img.url) {
//var src = img.url + "?width=" + newSize.width + "&height=" + newSize.height;
var src = img.url;
editor.dom.setAttrib(imgElm, 'data-mce-src', src);
}
}
}, 500);

HTML5 canvas on iPad (with Phonegap) not working as expected

I am developing an iPad application with Phonegap and jQuery mobile. One of the functions required is to allow the user of the app to sign (their signature) in 2 boxes. I am using easel.js to handle the "drawing" on the canvas element.
The HTML structure of this page is something like:
<div class="signature-wrapper sw1">
<canvas class="flexBox" id="myCanvas" width="240" height="240"></canvas>
</div>
<div class="signature-wrapper sw2">
<canvas class="flexBox" id="myCanvas2" width="240" height="240"></canvas>
</div>
Where the 2 canvas elements are where the signatures will be drawn. Below each of these elements are buttons to clear and save each of the elements. When clicked, they fire functions to clear the canvas, or save the canvas to an image (the image is then placed over the canvas, and removed on clear)
The save functionality looks something like:
function saveStage1(){
var canvas = document.getElementById("myCanvas");
var imageData = canvas.toDataURL("image/png");
$('.sw1').append("<img src='" + imageData +"' style='position: absolute; left: 0px; top: 0px;' />");
}
Basically, it is just getting the content of the canvas and saving it to a PNG image, which is then appended to the wrapper for the canvas elements. There is additional code I have left out of the code here for clarity, dealing with localStorage and db.transactions.
This function is working as expected.
The next function is to clear the canvas:
function clearStage1(){
oldMidX, oldMidY, oldX, oldY = null;
delete window.currentShape;
stage.clear();
stage.removeAllChildren();
stage.update();
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'images/signature-client.png';
$('.sw1 img').remove();
}
This clears the canvas, nulls some variables, and recreates the canvas.
This works 100% in chrome and safari, but does not work correctly on iPad as a Phonegap application. On iPad, you can draw, but once you have clicked save or clear you are unable to draw without navigating away and back to the screen. It seems there is a JavaScript error somewhere on the page on both the save and clear functions which is preventing any further JavaScript from executing without "reloading" the page.
I have setup my console in Safari on mac to look at xcode application, and there is no error in the log. Any help would be appreciated.

Print large SVG chart on separate pages

I am trying to print a large SVG chart from a browser, the SVG chart is embedded into the HTML. The width / height of the chart is set to absolute. The print only prints a part of the SVG chart, however much will fit on 1 page, and cuts the rest off. Is there a way to split up the chart to print into separate pages?
This totally depends on what browser you are using to view the SVG. Either try a different browser... Safari has GREAT printing capabilities (on the Mac at least).. or... "isolate" the SVG.. Either look at the source and figure out the relative URL to the embedded SVG and enter it into the URL bar..
<td><object id="object" type="image/svg+xml" data="**smiley.svg**">Please use a modern browser!</object></td>
<td><iframe id="iframe" src="**smiley.svg**">Please use a modern browser!</iframe></td>
<td><embed id="embed" src="**smiley.svg**" type="image/svg+xml" /></td>
<td><img id="img" alt="smiley face" src="**smiley.svg**" /></td>
or Copy and paste the actual SVG code from the inline source and paste it into a plain text document with the .svg extension...
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice"
style="width:100%; height:100%; position:absolute; top:0; left:0; z-index:-1;">
<linearGradient id="gradient">
<stop class="begin" offset="0%"/>
<stop class="end" offset="100%"/>
</linearGradient>
<rect x="0" y="0" width="100" height="100" style="fill:url(#gradient)" />
<circle cx="50" cy="50" r="30" style="fill:url(#gradient)" />
</svg>
Then you can use a multitude of applications, from Illustrator, to the free Inkscape, or MANY, many others to manipulate (or print) it to your hearts content.
Use phantomjs.org project to generate your chart images at server.
It allows to load any HTML page by URL into headless WebKit machine and render it into PNG.
Plus, you can get final size of your page and then cut it into peaces via defining Clip Region in cycle.
For example next sample exports several charts from the page into separate PNG images in file system. After that you can assemble your new web page or pack them into PDF and provide download link to your user. This would be the most reliable and stable printing solution for web application.
var page = require('webpage').create();
page.viewportSize = { width: 1280, height : 1024 };
page.open('http://chart.html', function () {
page.clipRect = page.evaluate(function () {
var chart = jQuery("#chart1");
return { top: chart.offset().top, left: chart.offset().left, width: chart.outerWidth(), height: chart.outerHeight() };
});
page.render('chart1.png');
page.clipRect = page.evaluate(function () {
var chart = jQuery("#chart2");
return { top: chart.offset().top, left: chart.offset().left, width: chart.outerWidth(), height: chart.outerHeight() };
});
page.render('chart2.png');
page.clipRect = page.evaluate(function () {
var chart = jQuery("#chart3");
return { top: chart.offset().top, left: chart.offset().left, width: chart.outerWidth(), height: chart.outerHeight() };
});
page.render('chart3.png');
phantom.exit();
});

Resources