I am developing a mobile (iphone/android) application using appcelerator titanium (sdk 1.6.2).
At a certain point in the app the user choses an image that should be shown in an imageView, base64 encoded, then uploaded to my server.
The problem is the success event of the photo gallery returns the selected image as a blob object and the Titanium.Utils.base64encode method only accepts string values!
Is there any way to convert Titanium.Blob objects to strings?
Here is the code snippet:
var imageView = Titanium.UI.createImageView({
height:200,
width:200,
top:20,
left:10,
backgroundColor:'#999'
});
Titanium.Media.openPhotoGallery({
success:function(event)
{
var cropRect = event.cropRect;
var image = event.media;//blob object
// set image view
Ti.API.debug('Our type was: '+event.mediaType);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
{
imageView.image = image;// this works
var imgStr=Ti.Utils.base64encode(image);// doesn't work because 'image' has to be a string!, but how?
}
else
{
}
Titanium.API.info('PHOTO GALLERY SUCCESS cropRect.x ' + cropRect.x + ' cropRect.y ' + cropRect.y + ' cropRect.height ' + cropRect.height + ' cropRect.width ' + cropRect.width);
},
allowEditing:true,
popoverView:popoverView,
arrowDirection:arrowDirection,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]
});
Thank you,
var imgStr=Ti.Utils.base64encode(image.toString());
.toString() converts something to a string representation
This worked for me.
var image = event.media;
var imgStr = Ti.Utils.base64encode(image).toString();
i just posted some code for a module to do this conversion, I know a patch is coming from appcelerator, but the module might be useful to you now.
Clearly Innovative Thoughts - Titanium Appcelerator Quickie: base64encode iOS Module
Related
I have an url that gets team logos but it returns svg https://www.mlbstatic.com/team-logos/141.svg.
How can i display this in a Image for xamarin forms?
Searched and only found complex huge amounts of code.
looking for
Download image -- I have this but what do i need to save it in GetResponsestream preferrable i would like to stay in memory and not write to disk or file.
Attach it to an image to display.
Thanks.
Ok, thought i would post my solution here.
I used SkiSharp:
SkiaSharp.Extended.Svg.SKSvg svg = new SkiaSharp.Extended.Svg.SKSvg();
using (WebClient client = new WebClient())
{
// ie for theurl: https://www.mlbstatic.com/team-logos/141.svg
svg.Load(new MemoryStream(client.DownloadData(new Uri(theurl))));
var bitmap = new SKBitmap((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height);
var canvas = new SKCanvas(bitmap);
canvas.DrawPicture(svg.Picture);
canvas.Flush();
canvas.Save();
string filename = "";
using (var image = SKImage.FromBitmap(bitmap))
using (var data = image.Encode(SKEncodedImageFormat.Png, 80))
{
// save the data to a stream
filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.png");
using (var stream = File.OpenWrite(filename ))
{
data.SaveTo(stream);
}
}
}
use FileName from above to assign source to Xamarin image.
this accomplished the task with the least amount of code lines i tried.
My environment is node v12.16.1 with typescript added.
I am using pdf-lib v1.16.0 (https://www.npmjs.com/package/pdf-lib) in order to fill the form for given PDF file. Library source code can be found here https://github.com/Hopding/pdf-lib and more on docs here https://pdf-lib.js.org/.
Regarding fonts pdf-lib has a set of called StandardFonts which is provided inside the lib.
export enum StandardFonts {
Courier = 'Courier',
CourierBold = 'Courier-Bold',
CourierOblique = 'Courier-Oblique',
CourierBoldOblique = 'Courier-BoldOblique',
Helvetica = 'Helvetica',
HelveticaBold = 'Helvetica-Bold',
HelveticaOblique = 'Helvetica-Oblique',
HelveticaBoldOblique = 'Helvetica-BoldOblique',
TimesRoman = 'Times-Roman',
TimesRomanBold = 'Times-Bold',
TimesRomanItalic = 'Times-Italic',
TimesRomanBoldItalic = 'Times-BoldItalic',
Symbol = 'Symbol',
ZapfDingbats = 'ZapfDingbats',
}
Very often you would have requirement to apply font which is not on the list. One example is when you have some user documents/forms to fill and then to apply electronical signature on it in order to approve them. Sometimes that electronic signature can be of a different font type, chosen by the user.
So, how we can add new font type of our choice?
From the specs https://www.npmjs.com/package/pdf-lib#embed-font-and-measure-text
pdf-lib relies on a sister module to support embedding custom fonts:
#pdf-lib/fontkit. You must add the #pdf-lib/fontkit module to your
project and register it using pdfDoc.registerFontkit(...) before
embedding custom fonts.
We have to npm i --save #pdf-lib/fontkit and we have to have source from where which we will read the font. In my case I have added .otf file in project and loaded font. Files are structured like on the image:
import path from 'path';
import fs from 'fs';
import {PDFDocument, PDFForm, StandardFonts, PDFFont} from 'pdf-lib';
import fontkit from '#pdf-lib/fontkit';
const pdfBytes = fs.readFileSync(path.join(__dirname, `/w_template/` + fileName + '.pdf'));
const pdfDoc = await PDFDocument.load(pdfBytes);
pdfDoc.registerFontkit(fontkit);
//load font and embed it to pdf document
const fontBytes = fs.readFileSync(path.join(__dirname, 'HouschkaHead-BoldItalic.otf'));
const customFont = await pdfDoc.embedFont(fontBytes);
const form = pdfDoc.getForm();
const textField = form.getTextField('signature');
textField.setFontSize(11);
textField.setText('stefan z');
textField.updateAppearances(customFont);
// form flatten is available from v1.16.0 and it makes form read-only (not editable)
form.flatten();
const modifiedPdf = await pdfDoc.save();
And this is the final result: check how the signature input form field is different from rest of input fields which are filled with default font
Bonus: if you want to play with color of the text of inputs in form, this is what I have found while digging more under the library source code (it might be not optimal, but it can give you starting point for more things):
import {setFillingRgbColor} from 'pdf-lib'
const textField = form.getTextField(fieldName);
const da = textField.acroField.getDefaultAppearance() ?? '';
const newDa = da + '\n' + setFillingRgbColor(1, 0, 0).toString();
textField.acroField.setDefaultAppearance(newDa);
If anyone is struggling to change the fontSize in filling text fields using the latest inbuilt function called setFontSize(). You can use this approach.
const { PDFDocument, setFontAndSize } = require('pdf-lib');
const pdfDoc = await PDFDocument.load(file);
const form = pdfDoc.getForm();
const textField = form.getTextField('106Mobile.1');
textField.setText('This works fine');
const da = textField.acroField.getDefaultAppearance() ?? '';
const newDa = da + '\n' + setFontAndSize('Courier', 8).toString(); //setFontAndSize() method came to resuce
textField.acroField.setDefaultAppearance(newDa);
I had to use this because I got an error saying
No /DA (default appearance) entry found for field: 106Title.1
when setting font sizes to some text fields (not all of it). But I degenerately had those text fields. Fixed it using the above workaround.
In nativescript(with angular) is there any way to set the src of an image from the response of a web api call that returns the image as byte array/base64?
There is not to much documentation, and I need to see the html and .ts files from a simple example, I have no code to paste here now.
you need to first create ImageSource form base64 string and then assign that imageSource to Image Native Element.
let imageSource = new ImageSource();
let loadedSource64 = imageSource.loadFromBase64(BASE_64_STRING_FROM_API_CALL);
if (loadedSource64 ) {
let image= <Image>this.imageElement.nativeElement;
image.imageSource = this.imageSource;
}
I would like to use the Autodesk Design Automation API to extract all Text and Header information from a .dwg file into a json object. Is this possible with the Design Automation API?
Any example would help.
Thankyou
#Kaliph, yes, without a plugin in .NET/C++/Lisp code, it is impossible to extract block attributes by script only. I'd recommend .NET. It would be easier for you to get started with if you are not familiar with C++.
Firstly, I'd suggest you take a look at the training labs of AutoCAD .NET API:
https://www.autodesk.com/developer-network/platform-technologies/autocad
pick the latest version if you installed a latest version of AutoCAD. The main workflow of API is same across different versions, though. you can also pick C++ (ObjectARX) if you like.
In the tutorials above, it demos how to work with block. And the blog below talks about how to get attributes:
http://through-the-interface.typepad.com/through_the_interface/2006/09/getting_autocad.html
I copied here for convenience:
using Autodesk.AutoCAD;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
namespace MyApplication
{
public class DumpAttributes
{
[CommandMethod("LISTATT")]
public void ListAttributes()
{
Editor ed =
Application.DocumentManager.MdiActiveDocument.Editor;
Database db =
HostApplicationServices.WorkingDatabase;
Transaction tr =
db.TransactionManager.StartTransaction();
// Start the transaction
try
{
// Build a filter list so that only
// block references are selected
TypedValue[] filList = new TypedValue[1] {
new TypedValue((int)DxfCode.Start, "INSERT")
};
SelectionFilter filter =
new SelectionFilter(filList);
PromptSelectionOptions opts =
new PromptSelectionOptions();
opts.MessageForAdding = "Select block references: ";
PromptSelectionResult res =
ed.GetSelection(opts, filter);
// Do nothing if selection is unsuccessful
if (res.Status != PromptStatus.OK)
return;
SelectionSet selSet = res.Value;
ObjectId[] idArray = selSet.GetObjectIds();
foreach (ObjectId blkId in idArray)
{
BlockReference blkRef =
(BlockReference)tr.GetObject(blkId,
OpenMode.ForRead);
BlockTableRecord btr =
(BlockTableRecord)tr.GetObject(
blkRef.BlockTableRecord,
OpenMode.ForRead
);
ed.WriteMessage(
"\nBlock: " + btr.Name
);
btr.Dispose();
AttributeCollection attCol =
blkRef.AttributeCollection;
foreach (ObjectId attId in attCol)
{
AttributeReference attRef =
(AttributeReference)tr.GetObject(attId,
OpenMode.ForRead);
string str =
("\n Attribute Tag: "
+ attRef.Tag
+ "\n Attribute String: "
+ attRef.TextString
);
ed.WriteMessage(str);
}
}
tr.Commit();
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
ed.WriteMessage(("Exception: " + ex.Message));
}
finally
{
tr.Dispose();
}
}
}
}
I have a sample on making signs on a drawing. It covers getting attributes and modifying attributes:
https://forge.autodesk.com/cloud_and_mobile/2016/02/sign-title-block-of-dwg-file-with-autocad-io-view-data-api.html
And I also have a sample on getting Table cells of a drawing:
https://forge.autodesk.com/blog/get-cell-data-autocad-table-design-automation-api
Hope these could help you to make the plugin for your requirements.
What do you mean by "Header" information? Can you give an example?
Finding an extracting all text objects is relatively easy if you are familiar with the AutoCAD .NET API (or C++ or Lisp).
Here's an example that extracts blocks and layer names:
https://github.com/Autodesk-Forge/design.automation-.net-custom.activity.sample
I have a Flash Professional CS5 movie which I'm trying to pass a parameter with swfobject. The problem is that movieclip's flashvar variables (under loaderInfo.parameters) is null.
Here is the swfobject code:
function loadSetupBar(connectId)
{
// add the setup bar to the DOM using swfobject
swfobject.embedSWF("{{setupBarSwf}}",
"swf-setup-bar",
{{gameWidth}}, $("#top-bar").height(),
"10.0.0", "{{installSwf}}",
{connectionId : connectId },
{
allowFullScreen : true,
wmode : 'opaque',
allowscriptaccess: "always"
},
{name:"swf-setup-bar"}
);
}
According to the swfobject documentation, everything seems to be ok.
Here's the corresponding code inside the FLA (A MovieClip with its own AS3 class):
var params : Object = root.loaderInfo.parameters;
var connectionId : String = params.connectionId;
if ( !params.hasOwnProperty('connectionId') )
// this line is always printed.
trace("[SetupBar-Error] loaderInfo parameters missing property 'connectionId'")
I'm not sure about what else to do.
Thanks.
EDIT: Here is a list of things I've tried that have failed:
casted root.loaderInfo to class LoaderInfo ( i.e. LoaderInfo(this.root.loaderInfo) )
passing a String literal in swfobject.embedSWF instead of param connectId
(i.e. {connectionID : 'myTestValue'})
There's a problem with the TLF TEXT control, when you add it to the stage the flashvars begins not working . just don't use it and your flashvars will work fine . i've faced the same problem and i got it solved by not using TLF TEXT control.
I hope i helped .
Best Regards
Try this:
var params:Object = LoaderInfo(this.root.loaderInfo).parameters;
var connectionID:String = params.connectionId;