WinXP Only Bitmap.Save ArgumentException Parameter Not Valid - c#-4.0

Basically the code is trying to take a source image, draw some custom text on it and save the new image to the file system.
When I run the code in Windows 7, it runs fine, but when I run it in WinXP it creates an exception in the imgCopy.Save line anytime after the first DrawString.
The exception is ArgumentException (parameter is not valid). It's like the DrawString corrupts the image under WinXP...?
The build is for the x86/.NET 4.0 runtime. Any ideas why the exception under XP?
// imgSrc is actually passed into the method with the rec object
// this is just for repro
using (var imgSrc = new System.Drawing.Bitmap(rec.SrcFile))
using (var imgCopy = imgSrc.Clone() as Bitmap)
using (var gImg = Graphics.FromImage(imgCopy)) //shorten var names for this post
{
imgCopy.Save(rec.DstFile, ImageFormat.Jpeg); //Happy here
gImg.SmoothingMode = SmoothingMode.AntiAlias;
imgCopy.Save(rec.DstFile, ImageFormat.Jpeg); //Also no problem
gImg.DrawString(rec.Name, fntArial16, Brushes.Black, new Rectangle(170, 105, 650, 50), sfCenter);
imgCopy.Save(rec.DstFile, ImageFormat.Jpeg); //<-- Fails here
}
Edit: Code for the parameters:
private static Font fntArial16 = new Font("Arial", 16, FontStyle.Bold);
private static StringFormat _sfCenter;
private static StringFormat sfCenter {
get {
if (_sfCenter == null) {
_sfCenter = new StringFormat();
sfCenter.Alignment = StringAlignment.Center;
sfCenter.LineAlignment = StringAlignment.Center;
}
return _sfCenter;
}
}

We narrowed the problem down to the .jpg file containing XMP (Extensible Metadata Platform) data. Once we removed that from the file it worked on WinXP correctly. Unfortunately the tool that generated the file didn't have the option to exclude this, so we went with the .png file instead and that works fine as well.

Related

Need to dispaly svg on an image in Xamarin

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.

How to Find the Image That is not Found on Ios

I'm getting the error below when I reopen the application to see the image:
Could not initialize an instance of the type 'UIKit.UIImage': the native 'initWithContentsOfFile:' method returned nil
Is it possible to ignore this condition by setting
MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure
to false?
Below method is used to displaying the image
private async Task DisplayImageFromImageUrl()
{
UIImage image;
image = new UIImage(eventImageEntity.EventsImageUrl);
}
while executing the above code "image" showing "null" value.
If your trying to create an image from a URL, you need to use the following code:
if (!string.IsNullOrEmpty(eventImageEntity.EventsImageUrl.Trim()))
{
var url = new NSUrl(eventImageEntity.EventsImageUrl);
using (var data = NSData.FromUrl(url))
{
UIImage image = UIImage.LoadFromData(data);
}
}
Otherwise you will just end up with a Null UIImage. That is what's causing your problem.
EDIT:
If you're trying to get the image from a resource location, then the following is necessary:
This assumes that it's from a specific user created folder:
UIImage image = UIImage.FromFile(#"Assets/NavigationBarAssets/HomePC.png")
OR
This assumes that the image is just say in the root of iOS 'Resources' folder
UIImage image = new UIImage("HomePC.png")

IText, batik and vaadin charts scales wrong on linux

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.

How to load a txt file in MVC 5 respecting indentation and feed lines?

I am trying to load a text file in MCV5, I saw this piece of code works well
public ActionResult ReleaseNotes()
{ var fileContents = System.IO.File.ReadAllText(Server.MapPath(#"~/App_Data/ReleaseNotes.txt"));
return Content(fileContents); }
but I get something like:
Fixed an error in the user information tool introduced in 3.7.3--------------------------v 03.07.03--------------------------- Change 'Last Logon' to 'Last Connection' in the top right navigation web menu- Disable Shared Configuration admin page, when Shared Configuration feature is deactivated
instead of respecting the indentation and the feed lines of the original format
Fixed an error in the user information tool introduced in 3.7.3
--------------------------v 03.07.03---------------------------
Change 'Last Logon' to 'Last Connection' in the top right navigation web menu- Disable Shared Configuration admin page, when Shared Configuration feature is deactivated.
I have tried many solutions like:
public string ReleaseNotes()
{
string line,returnline="";
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(#"~\App_Data\ReleaseNotes.txt");
while ((line = file.ReadLine()) != null)
returnline = returnline + line + "\t\n";
file.Close();
return returnline;}
Do you know if there is a special class that manages only text files and respects the original format ?
thanks and Regards,
You must modify the controller and the view using a ViewBag to export the datas like that
In the controller
string line;
System.IO.StreamReader file = new System.IO.StreamReader(#"your file txt");
var fileLines = new List<string>();
while ((line = file.ReadLine()) != null)
{
fileLines.Add(line);
ViewBag.File = fileLines;
return View();
In the View (cshtml file)
#{
string line;
foreach (var item in ViewBag.File)
{
<p>#item</p>
}}
It should work properly

GET TEXT FROM IMAGE EMBEDDED IN A .docx FILE USING TIKA

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.

Resources