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.
Related
We use Adobe Acrobat to add fields to a PDF. We want to be able to access these fields and reference their exact location so we can stamp content in their location after getting the PDF back from DocuSign. We do this by manipulating the PDF's bytes using the C# ITextSharp Text PDF library. Unfortunately, opening the PDF in Adobe Acrobat once it's returned reveals that all fields are removed from our document.
Our C# populates most of these fields with text data from our database. 2 fields are left blank, because we want to use C# to superimpose a static image of someone's signature over their location after the document has been signed via DocuSign.
This is okay for what's populated before DocuSign gets our document, because removing the field doesn't visually omit data previously entered into these fields. This is NOT fine when it comes time for us to stamp our static signature image into the document. Our usage of ITextSharp relies on finding a field with a particular Adobe Acrobat ID, getting its location, and "stamping" a static image in that location.
Is there a way to tell DocuSign that we want to maintain all of our PDF fields, their locations, and their IDs?
public byte[] StampStaticSignature(byte[] documentBytes)
{
var signatureContainer = new SignatureContainer();
var signatureBytes = signatureContainer.GetSignatureBytes();
var reader = new PdfReader(documentBytes);
var updatedForm = new byte[] { };
using var stream = new MemoryStream();
var stamper = new PdfStamper(reader, stream);
var pdfFormFields = stamper.AcroFields;
var signatureImage = GetImageFromStream(signatureBytes);
//_adobeSignatureFields is a list of strings used to
//identify the signature fields by their ID set in Adobe Acrobat.
foreach (var signatureField in _adobeSignatureFields)
{
var sigPosition = pdfFormFields.GetFieldPositions(signatureField);
var page = sigPosition[0];
var x1 = sigPosition[1];
var y1 = sigPosition[2];
var x2 = sigPosition[3];
var y2 = sigPosition[4];
var contentBytes = stamper.GetOverContent((int)page);
var signatureFieldHeight = y2 - y1;
var signatureFieldWidth = x2 - x1;
signatureImage.ScaleToFit(signatureFieldWidth, signatureFieldHeight);
signatureImage.SetAbsolutePosition(x1, y1);
contentBytes.AddImage(signatureImage);
}
stamper.FormFlattening = false;
stamper.Close();
reader.Close();
updatedForm = stream.ToArray();
stream.Dispose();
return updatedForm;
}
Hank, as Inbar mentioned already we will need to examine your code and your API logs to see what could be going wrong. It is very hard to say what went wrong, especially when using 3rd party software like ITextSharp. I'd suggest opening a case with us by visiting our support center and adding a reference to case 09033616
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've been having some trouble getting my charts out to PDF.
Recently i posted this: Generating PDF with iText and batik which was solved as suggested with some tweaking to the scales.
I run amy testenviroment on a local glassfishserver on a windows 10 machine, and when I export to PDF I actually get a pretty result now.
But when I pushed the results to the RHEL server, the results differed. The charts shown on the website is great, but when I export to pdf, I get this:
As you can see, the title is pushed down, for some reason the Y-axis with labels are cropped, and the data-labels are squished together. I've tried playing around with different scales, with and without scaletofit, scaletoabsolute and so on, but no matter what I do, it keeps doing that weird thing.
Does anybody has any idea whats going on - and even better, how to fix it? I've doublechecked that phantomjs is the same version, to make sure the SVG is the right one-.
The code is as follows:
private Image createSvgImage(PdfContentByte contentByte, Chart chart) throws IOException {
Configuration configuration = chart.getConfiguration();
configuration.setExporting(false);
SVGGenerator generator = SVGGenerator.getInstance();
generator.withHeigth(600);
generator.withWidth(1200);
String svg = generator.generate(configuration);
Image image = drawUnscaledSvg(contentByte, svg);
image.scaleToFit(800, 370);
configuration.setExporting(true);
return image;
}
private Image drawUnscaledSvg(PdfContentByte contentByte, String svgStr) throws IOException {
GraphicsNode imageGraphics = buildBatikGraphicsNode(svgStr);
float width = 1200;
float height = 600;
PdfTemplate template = contentByte.createTemplate(width, height);
Graphics2D graphics = template.createGraphics(width, height);
try {
imageGraphics.paint(graphics);
graphics.translate(-10, -10);
return new ImgTemplate(template);
} catch (BadElementException e) {
throw new RuntimeException("Couldn't generate PDF from SVG", e);
} finally {
graphics.dispose();
}
}
private GraphicsNode buildBatikGraphicsNode(String svgStr) throws IOException {
UserAgent agent = new UserAgentAdapter();
SVGDocument svgdoc = createSVGDocument(svgStr, agent);
DocumentLoader loader = new DocumentLoader(agent);
BridgeContext bridgeContext = new BridgeContext(agent, loader);
bridgeContext.setDynamicState(BridgeContext.STATIC);
GVTBuilder builder = new GVTBuilder();
GraphicsNode imageGraphics = builder.build(bridgeContext, svgdoc);
return imageGraphics;
}
private SVGDocument createSVGDocument(String svg, UserAgent agent)
throws IOException {
SVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(
agent.getXMLParserClassName(), true);
SVGDocument svgdoc = documentFactory.createSVGDocument(null,
new StringReader(svg));
return svgdoc;
}
UPDATE I've tried reading a SVG file from disk, that I knew was correct, and that is put correctly within the PDF. So the problem lies somewhere within the SVG Generator. Anyone knows about this?
Using an older version of PhantomJS (1.9.8) fixes the problem.
I've made a ticket with Vaadin.
I've been working on Text Extractor that works on .docx file using Tika. And it is working file for basic text and text in tables and textboxes, but it fails for images.
How do I get text from Image, tesseract along with tika can be used to get text from an image alone but for that I would need to extract out the image from document. How do I do this?
Kindly help if anybody has worked upon something like this.
This the code that works fine for text, textbox and tables,but not for images:
public class BasicDocumentExtractor {
public static void main(final String[] args) throws IOException,SAXException, TikaException {
//detecting the file type
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
FileInputStream inputstream=new FileInputStream(new File("D:\\Nidhi\\sw\\ws\\Hello.docx"));
ParseContext pcontext=new ParseContext();
//OOXml parser
OOXMLParser msofficeparser=new OOXMLParser ();
msofficeparser.parse(inputstream, handler,metadata,pcontext);
System.out.println("Contents of the document:" +handler.toString());
/*System.out.println("Metadata of the document:");
String[] metadataNames = metadata.names();
for(String name : metadataNames){
System.out.println(name + ": " + metadata.get(name));
}*/
}
}
You need to enable recursion in Tika in order to get the embedded images. The simplest way is normally just to use the RecursiveParserWrapper to do it for you.
If you use it, your code would instead be roughly
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
TikaInputStream input = TikaInputStream.get(new File("D:\\Nidhi\\sw\\ws\\Hello.docx"));
Parser wrapped = new AutoDetectParser();
RecursiveParserWrapper wrapper = new RecursiveParserWrapper(wrapped,
new BasicContentHandlerFactory(BasicContentHandlerFactory.HANDLER_TYPE.TEXT, 60));
wrapper.parse(stream, handler, metadata, context);
// Get metadata from children
List<Metadata> list = wrapper.getMetadata();
// Get metadata from main document
System.out.println("Main doc name is " + metadata.get(TikaCoreProperties.TITLE));
System.out.println("Contents of the document:" +handler.String());
As I was trying really hard to do this since las 24hours, I figured out a way, a pretty easy one. Since, Tika is built on the top of POI, using POI this task can be efficiently executed. Also, it is not a direct solution so alomost no tutorials are available for this purpose, I hope nobody else has to face this issue in future. This is the running code that extracts all images from a .docx document:
public static void getImages() throws Exception {
XWPFDocument doc=new XWPFDocument(new FileInputStream("D:\\Nidhi\\CDAC\\Images\\test1.docx"));
List images=doc.getAllPictures();
int i =0;
while (i<images.size()) {
XWPFPictureData pic= (XWPFPictureData) images.get(i);
System.out.println(pic.getFileName() + " "+ pic.getPictureType() +" "+ pic.getData());
FileOutputStream fos=new FileOutputStream("D:\\Nidhi\\CDAC\\Images\\b" + i+".jpg");
fos.write(pic.getData());
i++;
}
}
Also, if it will work on all MS Office 2007+ files, for .doc and such files use HWPF in the exactly same manner.
i am recording video from webcam using DirectshowLib2005.dll in C#.net..i have this code to startVideoRecoding as below..
try
{
IBaseFilter capFilter = null;
IBaseFilter asfWriter = null;
IFileSinkFilter pTmpSink = null;
ICaptureGraphBuilder2 captureGraph = null;
GetVideoDevice();
if (availableVideoInputDevices.Count > 0)
{
//
//init capture graph
//
graphBuilder = (IFilterGraph2)new FilterGraph();
captureGraph = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
//
//sets filter object from graph
//
captureGraph.SetFiltergraph(graphBuilder);
//
//which device will use graph setting
//
graphBuilder.AddSourceFilterForMoniker(AvailableVideoInputDevices.First().Mon, null, AvailableVideoInputDevices.First().Name, out capFilter);
captureDeviceName = AvailableVideoInputDevices.First().Name;
//
//check saving path is exsist or not;if not then create
//
if (!Directory.Exists(ConstantHelper.RootDirectoryName + "\\Assets\\Video\\"))
{
Directory.CreateDirectory(ConstantHelper.RootDirectoryName + "\\Assets\\Video\\");
}
#region WMV
//
//sets output file name,and file type
//
captureGraph.SetOutputFileName(MediaSubType.Asf, ConstantHelper.RootDirectoryName + "\\Assets\\Video\\" + videoFilename + ".wmv", out asfWriter, out pTmpSink);
//
//configure which video setting is used by graph
//
IConfigAsfWriter lConfig = asfWriter as IConfigAsfWriter;
Guid asfFilter = new Guid("8C45B4C7-4AEB-4f78-A5EC-88420B9DADEF");
lConfig.ConfigureFilterUsingProfileGuid(asfFilter);
#endregion
//
//render the stram to output file using graph setting
//
captureGraph.RenderStream(null, null, capFilter, null, asfWriter);
m_mediaCtrl = graphBuilder as IMediaControl;
m_mediaCtrl.Run();
isVideoRecordingStarted = true;
VideoStarted(m_mediaCtrl, null);
}
else
{
isVideoRecordingStarted = false;
}
}
catch (Exception Ex)
{
ErrorLogging.WriteErrorLog(Ex);
}
if you observe this lines of code
//
//configure which video setting is used by graph
//
IConfigAsfWriter lConfig = asfWriter as IConfigAsfWriter;
Guid asfFilter = new Guid("8C45B4C7-4AEB-4f78-A5EC-88420B9DADEF");
lConfig.ConfigureFilterUsingProfileGuid(asfFilter);
it will apply video setting which is described on that GUID i got this GUID from file located at "C:\windows\WMSysPr9.prx"..
so my question is how create my own video setting with format,resolutions and all?
How to Record video using webcam in black and white mode or in grayscale?
so my question is how create my own video setting with format,resolutions and all?
GUID based profiles are deprecated, though you can still use them. You can build custom profile in code using WMCreateProfileManager and friends (you start with empty profile and add video and/or audio streams at your discretion). This is C++ API, and I suppose that WindowsMedia.NET, a sister project to DirectShowLib you are already using, provides you interface into .NET code.
Windows SDK WMGenProfile sample both shows how to build profile manually and provides you a tool to build it interactively and save into .PRX file you can use in your application.
$(WindowsSDK)\Samples\multimedia\windowsmediaformat\wmgenprofile
How to Record video using webcam in black and white mode or in grayscale?
The camera gives you a picture, then it goes through pipeline up to recording through certain processing. Ability to make it greyscale is not something inherent.
There are two things you might want to think of. First of all, if the camera is capable of stripping color information on capture, you can leverage this. Check it out - if its settings have Saturation slider, then you just put it input minimal value position and the camera gives you greyscale.
In code, you use IAMVideoProcAmp interface for this.
Another option, including if the camera is missing mentioned capability, is to apply post processing filter or effect that converts to greyscale. There is no stock solution for this, and otherwise there are several ways to achieve the effect:
use third party filter that strips color
export from DirectShow pipeline, convert data in code using Color Control Transform DSP (available starting Win Vista) or GDI functions
use Sample Grabber in the streaming pipeline and update image bits directly