How can I tell if the image returned from didFinishPickingMediaWithInfo was from the camera or the photoalbum? - uiimagepickercontroller

I have a view controller that needs to be able to choose a picture from the photo album and also from the camera. I can only have 1 delegate method for didFinishPickingMediaWithInfo and while I can tell if it's an image, I can't seem to tell if it's from the album or from the camera (and I need to save it in the album first). Is there anything in the info that can help me distinguish from the two?
Thanks...

Because the UIImagePickerController is passed to the method, all you have to do is:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
if ([picker sourceType] == UIImagePickerControllerSourceTypeCamera) {
// Do something with an image from the camera
} else {
// Do something with an image from another source
}
}

In Swift3:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if picker.sourceType == .camera {
// Do something with an image from the camera
}
else {
// Do something with an image from another source
}
}

Related

flutter with firebase - detect the url string whether it is image(jpg) or video(avi)

I'm beginner with these Google's products and got 'serious' problem.
I uploaded photos and videos to firebase storage and urls of the photos and videos in the firebase storage is generated and stored automatically in firebase database. In my flutter lib, I could call those urls by my own code and display the url's image on the avd screen.
Image.network(url) is the code to display image url from firebase. But I also wanna display video url's asset simultaneously with single code. That is, videos and photos should be in single screen! In this case, Image.network(url) doesn't work anymore..
If I change that image.network code for video format according to video_player plug-in, I cannot display image asset anymore and if I stay same with that Image.network(url) code, I cannot display video url from firebase. So here is the question:
How can I detect whether the firebase's url string is image or video with my flutter code, and display that asset on the 'single screen' whatever the file format is(at least video and photo) with integrated flutter code?
url example
It's not much of a deal since type of the media is in the URL. You can parse it as a
Uri object then extract the type.
import 'dart:core';
enum UrlType { IMAGE, VIDEO, UNKNOWN }
void main() async {
var imageUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.jpg?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
var videoUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.mp4?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
print(getUrlType(imageUrl));
print(getUrlType(videoUrl));
}
UrlType getUrlType(String url) {
Uri uri = Uri.parse(url);
String typeString = uri.path.substring(uri.path.length - 3).toLowerCase();
if (typeString == "jpg") {
return UrlType.IMAGE;
}
if (typeString == "mp4") {
return UrlType.VIDEO;
} else {
return UrlType.UNKNOWN;
}
}
Let me give you an idea.
Consider implementing this scenario.
var url = 'domain.com/file.jpg?querySegment';
In your widget area,
child: url.contains('.mp4?') ? VideoWidget() : ImageWidget()
also, even with multiple conditions,
child: (url.contains('.jpg?') || url.contains('.png?')) ? ImageWidget() : VideoWidget()
May this suits your case.
Improving upon the accepted answer, here is what I have in my code. I needed a way to identify many types of videos and images from the passed url.
Using path package to idetify the extension
Have a list of video and image extension
import 'package:path/path.dart' as p;
enum UrlType { IMAGE, VIDEO, UNKNOWN }
class UrlTypeHelper {
static List<String> _image_types = [
'jpg',
'jpeg',
'jfif',
'pjpeg',
'pjp',
'png',
'svg',
'gif',
'apng',
'webp',
'avif'
];
static List<String> _video_types = [
"3g2",
"3gp",
"aaf",
"asf",
"avchd",
"avi",
"drc",
"flv",
"m2v",
"m3u8",
"m4p",
"m4v",
"mkv",
"mng",
"mov",
"mp2",
"mp4",
"mpe",
"mpeg",
"mpg",
"mpv",
"mxf",
"nsv",
"ogg",
"ogv",
"qt",
"rm",
"rmvb",
"roq",
"svi",
"vob",
"webm",
"wmv",
"yuv"
];
static UrlType getType(url) {
try {
Uri uri = Uri.parse(url);
String extension = p.extension(uri.path).toLowerCase();
if (extension.isEmpty) {
return UrlType.UNKNOWN;
}
extension = extension.split('.').last;
if (_image_types.contains(extension)) {
return UrlType.IMAGE;
} else if (_video_types.contains(extension)) {
return UrlType.VIDEO;
}
} catch (e) {
return UrlType.UNKNOWN;
}
return UrlType.UNKNOWN;
}
}
/// Usage
if(UrlTypeHelper.getType(message) == UrlType.IMAGE) {
/// handle image
}
else if(UrlTypeHelper.getType(message) == UrlType.VIDEO) {
/// handle video
}

How to access Asset Catalog (images) after downloaded through NSBundleResourceRequest?

I cannot access images inside an asset catalog after it's been downloaded through NSBundleResourceRequest (on demand resource).
My code, say the image set name is "snow_4" with on demand resource tag "tag1"
NSBundleResourceRequest* resourceRequest = [[NSBundleResourceRequest alloc] initWithTags:[NSSet setWithObjects:#"tag1", nil]];
[resourceRequest conditionallyBeginAccessingResourcesWithCompletionHandler:
^(BOOL resourcesAvailable){
// if resource is not available download it
if (!resourcesAvailable) {
[resourceRequest beginAccessingResourcesWithCompletionHandler:
^(NSError * __nullable error){
if(!error){
UIImage* image = [UIImage imageNamed:#"snow_4"]; // image is null
}
}];
}else{
UIImage* image = [UIImage imageNamed:#"snow_4"]; // image is null
}
}];
Below is my Disk Report, please note that [UIImage imageNamed:#"snow_3"] (marked as 'In Use') returns a correct object but not images that are marked as 'Downloaded'
Appreciating your time and help!
Thanks,
Mars
Make sure NSBundleResourceRequest is not released early. Try to let NSBundleResourceRequest variable globally,
and access the image with UIImage(named: "xxx", in: self.bundleReq.bundle, compatibleWith: nil)
do this
image = [UIImage imageNamaed:#"snow_4" inBundle:[resourceRequest bundle]];
let tags = NSSet(array: ["tag1","tag2"])
let resourceRequest = NSBundleResourceRequest(tags: tags as! Set<String>)
resourceRequest.conditionallyBeginAccessingResourcesWithCompletionHandler {(resourcesAvailable: Bool) -> Void in
if resourcesAvailable {
// Do something with the resources
} else {
resourceRequest.beginAccessingResourcesWithCompletionHandler {(err: NSError?) -> Void in
if let error = err {
print("Error: \(error)")
} else {
// Do something with the resources
}
}
}
}

Sitecore: Show input option after using menu context item

I've added a menu context item to the TreelistEx. This menu item sends a messages that I later catch in a HandleMessage method.
In this method i create a new item ( template type and parent item are given in the source of the treelist field ).
All i need now is a way to ask the user for a name. But i haven't been able to find a simple way to do this.
class MyTreeListEx : TreelistEx, IMessageHandler
{
void IMessageHandler.HandleMessage(Message message)
{
if (message == null)
{ return; }
if (message["id"] == null)
{ return; }
if (!message["id"].Equals(ID))
{ return; }
switch (message.Name)
{
case "treelist:edit":
// call default treelist code
case "mytreelistex:add":
// my own code to create a new item
}
}
}
Does anyone have any suggestions on how to achieve this ?
Edit: added image & code + i'm using Sitecore 8 Update 1
I don't know which version of Sitecore you use but what you can try is SheerResponse.Input method.
You can use it like this:
using Sitecore.Configuration;
using Sitecore.Globalization;
using Sitecore.Shell.Applications.ContentEditor.FieldTypes;
using Sitecore.Web.UI.Sheer;
void IMessageHandler.HandleMessage(Message message)
{
...
case "mytreelistex:add":
Sitecore.Context.ClientPage.Start(this, "AddItem");
break;
}
protected static void AddItem(ClientPipelineArgs args)
{
if (args.IsPostBack)
{
if (!args.HasResult)
return;
string newItemName = args.Result;
// create new item here
// if you need refresh the page:
//SheerResponse.Eval("scForm.browser.getParentWindow(scForm.browser.getFrameElement(window).ownerDocument).location.reload(true)");
}
else
{
SheerResponse.Input("Enter the name of the new item:", "New Item Default Name", Settings.ItemNameValidation,
Translate.Text("'$Input' is not a valid name."), Settings.MaxItemNameLength);
args.WaitForPostBack();
}
}
This code will even validate your new item name for incorrect characters and length.

Flex Mobile 4.6 StageVideo not removing from stage

When I instantiate a new StageVideo instsance with stage.stageVideos[0] everything works great, but when i leave my view that's displaying the video it sticks on the stage. So when i goto another view it's still showing on the stage in the background. I tried setting sv = null, removing event listeners...etc.
I've created a StageVideoDisplay class which is instantiated in mxml like: and on view initialization i call a play() method:
if ( _path )
{
//...
// Connections
_nc = new NetConnection();
_nc.connect(null);
_ns = new NetStream(_nc);
_ns.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
_ns.client = this;
// Screen
_video = new Video();
_video.smoothing = true;
// Video Events
// the StageVideoEvent.STAGE_VIDEO_STATE informs you whether
// StageVideo is available
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY,
onStageVideoState);
// in case of fallback to Video, listen to the VideoEvent.RENDER_STATE
// event to handle resize properly and know about the acceleration mode running
_video.addEventListener(VideoEvent.RENDER_STATE, videoStateChange);
//...
}
On video stage event:
if ( stageVideoInUse ) {
try {
_rc = new Rectangle(0,0,this.width,this.height);
_sv.viewPort = _rc;
} catch (e:Error) {}
} else {
try {
_video.width = this.width;
_video.height = this.height;
} catch (e:Error) {}
}
And on stage video availability event:
protected function toggleStageVideo(on:Boolean):void
{
// To choose StageVideo attach the NetStream to StageVideo
if (on)
{
stageVideoInUse = true;
if ( _sv == null )
{
try {
_sv = stage.stageVideos[0];
_sv.addEventListener(StageVideoEvent.RENDER_STATE, stageVideoStateChange);
_sv.attachNetStream(_ns);
_sv.depth = 1;
} catch (e:Error) {}
}
if (classicVideoInUse)
{
// If you use StageVideo, remove from the display list the
// Video object to avoid covering the StageVideo object
// (which is always in the background)
stage.removeChild ( _video );
classicVideoInUse = false;
}
} else
{
// Otherwise attach it to a Video object
if (stageVideoInUse)
stageVideoInUse = false;
classicVideoInUse = true;
try {
_video.attachNetStream(_ns);
stage.addChildAt(_video, 0);
} catch (e:Error) {}
}
if ( !played )
{
played = true;
_ns.play(path);
}
}
What happens is in the view when i navigator.popView(), the stageVideo remains on the stage, even in other views, and when returning to that view to play a different stream the same stream is kind of "burned" on top. I can not figure out a way to get rid of it! Thanks in advance!
In Flash Player 11, Adobe added the dispose() method to the NetStream class.
This is useful to clear the Video or StageVideo object when you're done with it.
When you call the dispose() method at runtime, you may get an exception indicating that there is no property named dispose on the NetStream object.
This occurs because Flash Builder is not compiling the app with the proper SWF version. To fix that, just add this to your compiler directives:
-swf-version=13
In the new Flash Builder 4.7, we hopefully won't have to specify the SWF version to use the newer Flash Player features.
This seems to be the best solution, but if you can't use Flash 11 (or the latest Adobe AIR), some other work arounds would be:
set the viewPort of stage video object to a rectangle that has width=0 and height=0
since stage video appears underneath your app, you can always cover the viewport (with a background color or some DisplayObject)
Ok the issue was actually that, even though it seemed like stage video was in use since i got the "Accelerated" message in status, that it was actually the video render even running and classic video was actually in use. The only thing I needed to do was add stage.removeChild( _video ) to the close() event in the class!!

Display an ashx image using jQuery?

I've been trying to use the jQuery plugin Colorbox to display images I have in my DB through an ashx file. Unfortunately it just spits a bunch of gibberish at the top of the page and no image. Can this be done? Here is what I have so far:
$(document).ready
(
function ()
{
$("a[rel='cbImg']").colorbox();
}
);
...
<a rel="cbImg" href="HuntImage.ashx?id=15">Click to see image</a>
UPDATE:
My ashx file is writing the binary out:
context.Response.ContentType = "image/bmp";
context.Response.BinaryWrite(ba);
Colorbox has an option 'photo'. If you set this to true in your constructor then it will force it to render the photo.
$(target).colorbox({photo: true});
You should be setting the src attribute in the client side.
<img src="HuntImage.ashx?id=15" ..../>
The handler
public class ImageRequestHandler: IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
if(context.Request.QueryString.Count != 0)
{
//Get the stored image and write in the response.
var storedImage = context.Session[_Default.STORED_IMAGE] as byte[];
if (storedImage != null)
{
Image image = GetImage(storedImage);
if (image != null)
{
context.Response.ContentType = "image/jpeg";
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
}
}
private Image GetImage(byte[] storedImage)
{
var stream = new MemoryStream(storedImage);
return Image.FromStream(stream);
}
public bool IsReusable
{
get { return false; }
}
}
It appears that I can't do what I am trying using colorbox with an ashx image. If anyone finds a way please post it here.
I considered deleting the question but I will leave it up incase someone else runs into the same issue.
Find this function around line 124 (colorbox 1.3.15)
// Checks an href to see if it is a photo.
// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
function isImage(url) {
return settings.photo || /\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url);
}
On line 127, add |ashx after bmp in (gif|png|jpg|jpeg|bmp) so it reads like this:
// Checks an href to see if it is a photo.
// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
function isImage(url) {
return settings.photo || /\.(gif|png|jpg|jpeg|bmp|ashx)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url);
}
This is working just fine for me in Sitecore 6.2 :)

Resources