Blackberry webworks 10 using image from picture taken\uploaded - blackberry-10

I am stuck with an issue and I have no idea what to try next.
In My application I offer my user a choice to either take a photo or choose a photo from the gallery. This part works fine, the problem arises with the saving\reading of the photo. Lets take this from the camera invoke perspective.
function startCameraApp() {
PhotoTaken = false;
blackberry.event.addEventListener("onChildCardClosed", sharePhoto);
blackberry.invoke.invoke({
target: "sys.camera.card"
}, onInvokeSuccess, onInvokeError);
}
and in sharePhoto I have the following code...
function sharePhoto(request) {
var image = new Image();
image.src = "file://" + request.data;
image.onload = function () {
// Now here I need to read the image file and convert it into base64.
var resized = resizeMe(image); // the resizeMe function is given below and it simply makes my image smaller
var imagedata = resized.split("base64,");
sessionStorage.setItem("MyNewPicture", imagedata);
}
}
function resizeMe(img) {
var canvas = document.createElement('canvas');
var max_width = 600;
var max_height = 600;
var width = img.width;
var height = img.height;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > max_width) {
height = Math.round(height * max_width / width);
width = max_width;
}
} else {
if (height > max_height) {
width = Math.round(width * max_height / height);
height = max_height;
}
}
//resize the canvas and draw the image data into it
img.width = width;
img.height = height;
canvas.width = width;
canvas.height = height;
canvas.classname += "ui-hidden";
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL();
}
So the app runs and it takes the photo and everything seems fine, yet the data uploaded to local storage is simply a blank screen. It works 100% in the blackberry 10 simulator, but not on my device. On the device it saves an empty string.
Edit
Ok. So I added this to my function for testing purposes and I am still stuck and I don't know what to do...
function sharePhoto(request) {
var image = new Image();
image.src = "file://" + request.data;
image.onload = function () {
// Now here I need to read the image file and convert it into base64.
var resized = resizeMe(image); // the resizeMe function is given below and it simply makes my image smaller
var imagedata = resized.split("base64,");
alert(imagedata); // This returns a blank popup
sessionStorage.setItem("MyNewPicture", imagedata);
}
}

I believe when you use the split method it returns an array, so you'd access it like this:
var resized = resizeMe(image);
var imagedata = resized.split("base64,");
imagedata = imagedata[1]; // this gives you everything after the 'base64,' string
However, the main problem I see is that you're splitting the imagedata string which is removing the whole 'this is an image' prefix from the data.
When you display the imagedata as an image, you need to have the data:image/jpeg;base64,
prefix as well.
So that being said, your images source would be
data:image/jpeg;base64,<rest of base64 string here>

I needed to include an extra element in my application's config.xml.
<access subdomains="true" uri="file://accounts/"></access>
<access subdomains="true" uri="file://accounts/100/shared/camera/"></access>
This gives access to your application to these folders and their containting files. Simulator's does not require this permission.

Related

Scaling an image OSX Swift

Im currently trying to scale an image using swift. This shouldnt be a difficult task, since i've implemented a scaling solution in C# in 30 mins - however, i've been stuck for 2 days now.
I've tried googling/crawling through stack posts but to no avail. The two main solutions i have seen people use are:
A function written in Swift to resize an NSImage proportionately
and
resizeNSImage.swift
An Obj C Implementation of the above link
So i would prefer to use the most efficient/least cpu intensive solution, which according to my research is option 2. Due to option 2 using NSImage.lockfocus() and NSImage.unlockFocus, the image will scale fine on non-retina Macs, but double the scaling size on retina macs. I know this is due to the pixel density of Retina macs, and is to be expected, but i need a scaling solution that ignores HiDPI specifications and just performs a normal scale operation.
This led me to do more research into option 1. It seems like a sound function, however it literally doesnt scale the input image, and then doubles the filesize as i save the returned image (presumably due to pixel density). I found another stack post with someone else having the exact same problem as i am, using the exact same implementation (found here). Of the two suggested answers, the first one doesnt work, and the second is the other implementation i've been trying to use.
If people could post Swift-ified answers, as opposed to Obj C, i'd appreciate it very much!
EDIT:
Here's a copy of my implementation of the first solution - I've divided it into 2 functions:
func getSizeProportions(oWidth: CGFloat, oHeight: CGFloat) -> NSSize {
var ratio:Float = 0.0
let imageWidth = Float(oWidth)
let imageHeight = Float(oHeight)
var maxWidth = Float(0)
var maxHeight = Float(600)
if ( maxWidth == 0 ) {
maxWidth = imageWidth
}
if(maxHeight == 0) {
maxHeight = imageHeight
}
// Get ratio (landscape or portrait)
if (imageWidth > imageHeight) {
// Landscape
ratio = maxWidth / imageWidth;
}
else {
// Portrait
ratio = maxHeight / imageHeight;
}
// Calculate new size based on the ratio
let newWidth = imageWidth * ratio
let newHeight = imageHeight * ratio
return NSMakeSize(CGFloat(newWidth), CGFloat(newHeight))
}
func resizeImage(image:NSImage) -> NSImage {
print("original: ", image.size.width, image.size.height )
// Cast the NSImage to a CGImage
var imageRect:CGRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let imageRef = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
// Create a new NSSize object with the newly calculated size
let newSize = NSSize(width: CGFloat(450), height: CGFloat(600))
//let newSize = getSizeProportions(oWidth: CGFloat(image.size.width), oHeight: CGFloat(image.size.height))
// Create NSImage from the CGImage using the new size
let imageWithNewSize = NSImage(cgImage: imageRef!, size: newSize)
print("scaled: ", imageWithNewSize.size.width, imageWithNewSize.size.height )
return NSImage(data: imageWithNewSize.tiffRepresentation!)!
}
EDIT 2:
As pointed out by Zneak: i need to save the returned image to disk - Using both implementations, my save function writes the file to disk successfully. Although i dont think my save function could be screwing with my current resizing implementation, i've attached it anyways just in case:
func saveAction(image: NSImage, url: URL) {
if let tiffdata = image.tiffRepresentation,
let bitmaprep = NSBitmapImageRep(data: tiffdata) {
let props = [NSImageCompressionFactor: Appearance.imageCompressionFactor]
if let bitmapData = NSBitmapImageRep.representationOfImageReps(in: [bitmaprep], using: .JPEG, properties: props) {
let path: NSString = "~/Desktop/out.jpg"
let resolvedPath = path.expandingTildeInPath
try! bitmapData.write(to: URL(fileURLWithPath: resolvedPath), options: [])
print("Your image has been saved to \(resolvedPath)")
}
}
To anyone else experiencing this problem - I ended up spending countless hours trying to find a way to do this, and ended up just getting the scaling factor of the screen (1 for normal macs, 2 for retina)... The code looks like this:
func getScaleFactor() -> CGFloat {
return NSScreen.main()!.backingScaleFactor
}
Then once you have the scale factor you either scale normally or half the dimensions for retina:
if (scaleFactor == 2) {
//halve size proportions for saving on Retina Macs
return NSMakeSize(CGFloat(oWidth*ratio)/2, CGFloat(oHeight*ratio)/2)
} else {
return NSMakeSize(CGFloat(oWidth*ratio), CGFloat(oHeight*ratio))
}

Image clipping with path (scaling issue)

The app I am using for testing puposes is able to take a picture and save it as a PNG file. The next time the app is launched, it checks if a file is present and if it is, the image stored inside the file is used as the background view of the app. Up to this point all is OK.
I decided to add a clipping mask to this app and this where things go wrong.
The clipping itself works, but for some mysterious reason the clipped image gets expanded. If someone could tell me what I am doing wrong that would be very helpful.
Here is the relevant code (I can provide more information if ever needed):
if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) {
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
(imageDataSampleBuffer, error) -> Void in
if error == nil {
var localImage = UIImage(fromSampleBuffer: imageDataSampleBuffer)
var imageSize = CGSize(width: UIScreen.mainScreen().bounds.height * UIScreen.mainScreen().scale,
height: UIScreen.mainScreen().bounds.width * UIScreen.mainScreen().scale)
localImage = resizeImage(localImage!, toSize: imageSize)
imageSize = CGSize(width: imageSize.height, height: imageSize.width)
UIGraphicsBeginImageContext(imageSize)
CGContextRotateCTM (UIGraphicsGetCurrentContext(), CGFloat(M_PI_2))
localImage!.drawAtPoint(CGPoint(x: 0.0, y: -imageSize.width))
localImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Clipping code:
localImage = maskImage(localImage!,
path: UIBezierPath(CGPath: CGPathCreateWithEllipseInRect(UIScreen.mainScreen().bounds, nil)))
if let data = UIImagePNGRepresentation(localImage!) {
data.writeToFile(self.bmpFilePath, atomically: true)
}
} else {print("Error on taking a picture:\n\(error)")}
}
}
The maskImage function is this (taken from iOS UIImage clip to paths and translated to Swift) :
func maskImage(originalImage :UIImage, path:UIBezierPath) -> UIImage {
UIGraphicsBeginImageContextWithOptions(originalImage.size, false, 0);
path.addClip()
originalImage.drawAtPoint(CGPointZero)
let maskedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return maskedImage;
}
When the lines:
localImage = maskImage(localImage!,
path: UIBezierPath(CGPath: CGPathCreateWithEllipseInRect(UIScreen.mainScreen().bounds, nil)))
are commented out, I see what I expect.
Thaking the picture below and having it as background when relaunching the app.
But when they are present(not commented out), I get the background hereafter when relaunching the app (of course taking the same picture at start):
If things worked as they should the mouse should appear inside the elliptic clip with the same size as in the first picture (not magnified as it is now).

Create PDF of dynamic size with typography using UIView template(s)

I'm new but have managed to learn a lot and create a pretty awesome (I hope) app that's near completion. One of my last tasks is to create a PDF of dynamically generated user data. It has been the most frustrating part of this whole process as there is no real modern clear cut template or guide. Apple's documentation isn't very descriptive (and some parts I don't understand) and the Q/A here on stack and examples on Google all seem very case specific. I thought I almost had it by using a UIScrollView but the end result was messy and I couldn't get things to line up neat enough, nor did I have enough control.
I believe my flaws with this task are logic related and not knowing enough about available APIs, help on either is greatly appreciated.
I have dynamically created user content filling an NSArray in a subclass of a UIViewController. That content consists of Strings and Images.
I would like to use a UIView (I'm presuming in a .xib file) to create a template with header information for the first page of the PDF (the header information is dynamic as well), any page after that can be done via code as it really is just a list.
I have a small understanding of UIGraphicsPDF... and would like to draw the text and images into the PDF and not just take a screen shot of the view.
My trouble with getting this going is:
(I'm being basic here on purpose because what I have done so far has led me nowhere)
How do I find out how many pages I'm going to need?
How do I find out if text is longer than a page and how do I split it?
How do I draw images in the PDF?
How do I draw text in the PDF?
How do I draw both text and images in the PDF but padded vertically so there's no overlap and account for Strings with a dynamic number of lines?
How do I keep track of the pages?
Thank you for reading, I hoe the cringe factor wasn't too high.
So here we go. The following was made for OSX with NSView but it's easily adapatable for UIView (so I guess). You will need the following scaffold:
A) PSPrintView will handle a single page to print
class PSPrintView:NSView {
var pageNo:Int = 0 // the current page
var totalPages:Int = 0
struct PaperDimensions {
size:NSSize // needs to be initialized from NSPrintInfo.sharedPrintInfo
var leftMargin, topMargin, rightMargin, bottomMargin : CGFloat
}
let paperDimensions = PaperDimensions(...)
class func clone() -> PSPrintView {
// returns a clone of self where most page parameters are copied
// to speed up printing
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
// e.g. to draw a frame inside the view
let scale = convertSize(NSMakeSize(1, 1), fromView:nil)
var myContext = NSGraphicsContext.currentContext()!.CGContext
CGContextSetLineWidth(myContext, scale.height)
CGContextSetFillColorWithColor(myContext, NSColor.whiteColor().CGColor)
CGContextFillRect (myContext, rect)
rect.origin.x += paperDimensions.leftMargin
rect.origin.y += paperDimensions.bottomMargin
rect.size.width -= paperDimensions.leftMargin + paperDimensions.rightMargin
rect.size.height -= paperDimensions.topMargin + paperDimensions.bottomMargin
CGContextSetStrokeColorWithColor(myContext, NSColor(red: 1, green: 0.5, blue: 0, alpha: 0.5).CGColor)
CGContextStrokeRect(myContext, rect)
// here goes your layout with lots of String.drawInRect....
}
}
B) PSPrint: will hold the single PSPrintViews in an array and when done send them to the (PDF) printer
class PSPrint: NSView {
var printViews = [PSPrintView]()
override func knowsPageRange(range:NSRangePointer) -> Bool {
range.memory.location = 1
range.memory.length = printViews.count
return true
}
func printTheViews() {
let sharedPrintInfo = NSPrintInfo.sharedPrintInfo()
let numOfViews = printViews.count
var totalHeight:CGFloat = 0;//if not initialized to 0 weird problems occur after '3' clicks to print
var heightOfView:CGFloat = 0
// PSPrintView *tempView;
for tempView in printViews {
heightOfView = tempView.frame.size.height
totalHeight = totalHeight + heightOfView
}
//Change the frame size to reflect the amount of pages.
var newsize = NSSize()
newsize.width = sharedPrintInfo.paperSize.width-sharedPrintInfo.leftMargin-sharedPrintInfo.rightMargin
newsize.height = totalHeight
setFrameSize(newsize)
var incrementor = -1 //default the incrementor for the loop below. This controls what page a 'view' will appear on.
//Add the views in reverse, because the Y position is bottom not top. So Page 3 will have y coordinate of 0. Doing this so order views is placed in array reflects what is printed.
for (var i = numOfViews-1; i >= 0; i--) {
incrementor++
let tempView = printViews[i] //starts with the last item added to the array, in this case rectangles, and then does circle and square.
heightOfView = tempView.frame.size.height
tempView.setFrameOrigin(NSMakePoint(0, heightOfView*CGFloat(incrementor))) //So for the rectangle it's placed at position '0', or the very last page.
addSubview(tempView)
}
NSPrintOperation(view: self, printInfo: sharedPrintInfo).runOperation()
}
C) a function to perform printing (from the menu)
func doPrinting (sender:AnyObject) {
//First get the shared print info object so we know page sizes. The shared print info object acts like a global variable.
let sharedPrintInfo = NSPrintInfo.sharedPrintInfo()
//initialize it's base values.
sharedPrintInfo.leftMargin = 0
sharedPrintInfo.rightMargin = 0
sharedPrintInfo.topMargin = 0
sharedPrintInfo.bottomMargin = 0
var frame = NSRect(x: 0, y: 0, width: sharedPrintInfo.paperSize.width-sharedPrintInfo.leftMargin-sharedPrintInfo.rightMargin, height: sharedPrintInfo.paperSize.height-sharedPrintInfo.topMargin-sharedPrintInfo.bottomMargin)
//Initiate the printObject without a frame, it's frame will be decided later.
let printObject = PSPrint ()
//Allocate a new instance of NSView into the variable printPageView
let basePrintPageView = PSPrintView(frame: frame)
// do additional init stuff for the single pages if needed
// ...
var printPageView:PSPrintView
for pageNo in 0..<basePrintPageView.totalPages {
printPageView = basePrintPageView.clone()
//Set the option for the printView for what it should draw.
printPageView.pageNo = pageNo
//Finally append the view to the PSPrint Object.
printObject.printViews.append(printPageView)
}
printObject.printTheViews() //print all the views, each view being a 'page'.
}
The PDF drawing code:
import UIKit
class CreatePDF {
// Create a PDF from an array of UIViews
// Return a URL of a temp dir / pdf file
func getScaledImageSize(imageView: UIImageView) -> CGSize {
var scaledWidth = CGFloat(0)
var scaledHeight = CGFloat(0)
let image = imageView.image!
if image.size.height >= image.size.width {
scaledHeight = imageView.frame.size.height
scaledWidth = (image.size.width / image.size.height) * scaledHeight
if scaledWidth > imageView.frame.size.width {
let diff : CGFloat = imageView.frame.size.width - scaledWidth
scaledHeight = scaledHeight + diff / scaledHeight * scaledHeight
scaledWidth = imageView.frame.size.width
}
} else {
scaledWidth = imageView.frame.size.width
scaledHeight = (image.size.height / image.size.width) * scaledWidth
if scaledHeight > imageView.frame.size.height {
let diff : CGFloat = imageView.frame.size.height - scaledHeight
scaledWidth = scaledWidth + diff / scaledWidth * scaledWidth
scaledHeight = imageView.frame.size.height
}
}
return CGSizeMake(scaledWidth, scaledHeight)
}
func drawImageFromUIImageView(imageView: UIImageView) {
let theImage = imageView.image!
// Get the image as it's scaled in the image view
let scaledImageSize = getScaledImageSize(imageView)
let imageFrame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, scaledImageSize.width, scaledImageSize.height)
theImage.drawInRect(imageFrame)
}
func drawTextFromLabel(aLabel: UILabel) {
if aLabel.text?.isEmpty == false {
let theFont = aLabel.font
let theAttributedFont = [NSFontAttributeName: theFont!]
let theText = aLabel.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) as NSString
let theFrame = aLabel.frame
theText.drawInRect(theFrame, withAttributes: theAttributedFont)
}
}
func parseSubviews(aView: UIView) {
for aSubview in aView.subviews {
if aSubview.isKindOfClass(UILabel) {
// Draw label
drawTextFromLabel(aSubview as! UILabel)
}
if aSubview.isKindOfClass(UIImageView) {
// Draw image (scaled and at correct coordinates
drawImageFromUIImageView(aSubview as! UIImageView)
}
}
}
func parseViewsToRender(viewsToRender: NSArray) {
for aView in viewsToRender as! [UIView] {
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil)
parseSubviews(aView)
}
}
func createPdf(viewsToRender: NSArray, filename: String) -> NSURL {
// Create filename
let tempDir = NSTemporaryDirectory()
let pdfFilename = tempDir.stringByAppendingPathComponent(filename)
UIGraphicsBeginPDFContextToFile(pdfFilename, CGRectZero, nil)
// begin to render the views in this context
parseViewsToRender(viewsToRender)
UIGraphicsEndPDFContext()
return NSURL(string: pdfFilename)!
}
}
First, I made a xib file with a UIView that fit the dimensions of a single PDF page and for my header information. This size is 612 points wide by 790 points tall.
Then I added UILabels for all of the page 1 header information I want to use (name, address, date, etc.)
I took note of y position and height of the lowest UILabel for my header information and subtracted it from the amount of vertical space in a page.
I also took note of the font and font size I wanted to use.
Then I created a class called CreatePDF
In that class I created several variables and constants, the font name, the font size, the size of a page, the remaining vertical space after header information.
In that class I created a method that takes two different arguments, one is a dictionary that I used for header information, the other is an array of UIImages and Strings.
That method calls a few other methods:
Determine the vertical height required for the items in the array
To do this I created another two methods, one to determine the height of a UILabel with any given string and one to determine the height of an image (vertical and horizontal images having different heights the way that I scale them). They each returned a CGFloat, which I added to a variable in the method that kept track of all the items in array.
For each item that was “sized” I then added another 8 points to use as a vertical offset.
Determine how many pages will be needed
The above method returned a CGFloat that I then used to figure out if either all the items will fit on one page below the header or if another page will be needed, and if so, how many more pages.
Draw a UIView
This method accepts the above mentioned dictionary, array and an estimated number of pages. It returns an array of UIViews.
In this method I create a UIView that matches the size of one PDF Page, I run a loop for each page and add items to it, I check to see if an item will fit by comparing it’s y position and height with the reaming vertical space on a page by subtracting the current Y position from the page height then I add an item and keep track of it’s height and y position, If the remaining height won’t work and I’m out of pages, I add another page.
Send the array to draw a PDF
I create the PDF context here
I take the array of UIViews as an argument, for each view I create a PDF Page in the PDF Context and then iterate through it’s subviews, if it’s a UILabel I send it off to a function that draws the UILabel at it’s frame position with it’s text property as the string. I create an attributed front using the variables defined in the class earlier. If it’s an image I send it to another function that also uses it’s frame, however I have to send it to yet another function to determine the actual dimensions of the image that’s drawn inside the UIImage (it changes based on scaling) and I return that for where to draw the image (this happens above too to properly size it).
That’s pretty much it, in my case I created the PDF context with a file, then end up returning the file to whoever calls this function. The hardest part for me to wrap my head around was keeping track of the vertical positioning.
I’ll work on making the code more generic and post it up somewhere.

How to create a fullscreen size popup in Windows phone

Fullscreen I mean the popup usercontrol covers the whole cellphone screen, maximize. can this be done?
thx!
You can get the current width and height by Content.ActualHeight/Width property
here's a code snippet
public void showPopUp()
{
//get heigth and width
double height=Application.Current.Host.Content.ActualHeight;
double width = Application.Current.Host.Content.ActualWidth;
//child content
StackPanel stk = new StackPanel();
stk.Height = height; //set height
stk.Width = width; //set width
stk.Background = new SolidColorBrush(Colors.Red);
TextBlock txtblock = new TextBlock() { FontSize=40, Text="HELLO WORLD", TextWrapping=TextWrapping.Wrap};
stk.Children.Add(txtblock);
Popup _popup = new Popup();
_popup.Child = stk; //set child content
this.LayoutRoot.Children.Add(_popup);
_popup.IsOpen = true;
}
and then you get this result ;)
For Windows Phone 8.1 you can get the current Application width and height by Window.Current.Bounds
double height = Window.Current.Bounds.Height;
double width = Window.Current.Bounds.Width;

C# Image resize- quality losing

I have used a C# method to resize the image size.I have used several methods from the following links.
C# Simple Image Resize : File Size Not Shrinking
shrinking
Resize an Image C#
but quality is missing when re-sizing the image
Please help me to resolve the issue.
You could use WIC (Windows Imaging Component) instead of GDI+. Here's a nice blog post with an example.
First convert your Bitmap to an Image
Bitmap b = new Bitmap("asdf.jpg");
Image i = (Image)b;
then pass the image to this method to resize
public static Image ResizeImage(Image image, int width, int height, bool onlyResizeIfWider)
{
using (image)
{
// Prevent using images internal thumbnail.
image.RotateFlip(RotateFlipType.Rotate180FlipNone);
image.RotateFlip(RotateFlipType.Rotate180FlipNone);
if (onlyResizeIfWider == true)
if (image.Width <= width)
width = image.Width;
// Resize with height instead?
int newHeight = image.Height * width / image.Width;
if (newHeight > height)
{
width = image.Width * height / image.Height;
newHeight = height;
}
Image NewImage = image.GetThumbnailImage(width, newHeight, null, IntPtr.Zero);
return NewImage;
}
}
I hope this helps.