I'm creating code to download some images from the web using HtmlUnit.
But when I save the image with HtmlUnit the quality of the image is very low compared with the original image.
I used this code to save the img url to a file.
try {
HtmlImage imgX = (HtmlImage)
page.getByXPath("//img").get(0);
Thread.sleep(3000);
File imageFile = new File(dir +"/"+ name);
imgX.saveAs(imageFile);
System.out.println("Done!!!!");
} catch (Exception e) {
e.printStackTrace();
}
Are there other options to get the image with the best quality?
I tried using this:
How to convert an <img... in html to byte [] in Java
But the image was not created.
Get the WebResponse from HtmlImage:
InputStream inputStream = imgX.getWebResponse(true).getContentAsStream();
And then work directly on InputStream:
File imageFile = new File(dir +"/"+ Name);
FileOutputStream outputStream = new FileOutputStream(imageFile);
IOUtils.copy(inputStream, outputStream);
Related
I have a class that uses the devices camera to capture an image. My aim is to pass the captured image to a canvas on another layout.
This layout will then be saved along with a note entered into a textbox.I have figured out how to save the note and title and allow it to be opened but I'm not sure how I would go about passing the captured image to the layout and saving it along with the note.
Does anyone have any advice or pointers as to how I would go about this?
At the moment this is how I'm attempting to read the image file back to the layout after it is saved,but I'm not sure how to read a file into the canvas so obviously this solution isn't working yet:
if (NavigationContext.QueryString.ContainsKey("note"))
{
string s2 = ".jpg";
string filename = this.NavigationContext.QueryString["note"];
if (!string.IsNullOrEmpty(filename)) {
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile .GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.ReadWrite, store))
/*
if(filename.Contains(s2))
{
StreamReader reader = new StreamReader(stream);
this.capturedNoteCanvas = reader.ReadToEnd();
this.noteNameTb.Text = filename; reader.Close();
}
else
*/
{
StreamReader reader = new StreamReader(stream);
this.noteDataTb.Text = reader.ReadToEnd();
this.noteNameTb.Text = filename; reader.Close();
}
}
}
What I'm thinking is something like this:
Working wit CameraCaptureTask and Bitmaps
//Taking a writableBitmap object from cameracapturetask
void cameracapturetask_Completed(object sender, PhotoResult e)
{
try
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
WritableBitmap wb=new WritableBitmap (bmp.PixelWidth,bmp.PixelHeight);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
saving wb in storage
using (MemoryStream stream = new MemoryStream())
{
wb.SaveJpeg(stream, (int)bmp.PixelWidth, (int)bmp.PixelHeight, 0, 100);
using (IsolatedStorageFileStream local = new IsolatedStorageFileStream(App.PageName, FileMode.Create, mystorage))
{
local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
}
}
//Taking a WritableBitmap from canvas
If your canvas is containing the image, and also the canvas it attributed with some height and width properties then
WritableBitmap wb= new WritableBitmap(canvascontrol,null);
takes the canvas and saves it inside a writablebitmap object which can then be used for further image manipulations.
i've been doing a essay about windowsphone. i created a address variable include a uri to add a image into address. There is a error when i use Isolate storage to save data. I don't know why.
Please help me!
Thank you so much.
class Address
{
private string name;
private Uri icon;
.....
}
......
public void save()
{
XmlWriterSettings xmlwritersetting = new XmlWriterSettings();
xmlwritersetting.Indent = true;
using (IsolatedStorageFile myisolatedstiragefile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myisolatedstiragefile.FileExists(filename))
{
myisolatedstiragefile.DeleteFile(filename);
}
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, System.IO.FileMode.OpenOrCreate, myisolatedstiragefile))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Adress>));
using (XmlWriter writer = XmlWriter.Create(stream, xmlwritersetting))
{
serializer.Serialize(writer, listadress);
}
}
}
}
It's a little difficult for me to understand your question, but I'll try. You really should indicate what error you specifically get in the debugger and where it occurs.
But just by looking, it seems that you might be trying to use the XmlSerializer to write binary image data to iso-storage and that probably won't work. You can find many examples of using iso-storage for various purposes including writing image files here:
http://www.windowsphonegeek.com/tips/All-about-WP7-Isolated-Storage---Read-and-Save-Images
For example, it shows that you can save a JPG image to isolated storage by doing this:
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
if (myIsolatedStorage.FileExists(tempJPEG)) {
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85); fileStream.Close();
}
I'm trying load image from Picture Hub through this...
void photoChooser_Completed(object sender, PhotoResult e)
{
try
{
var imageVar = new BitmapImage();
imageVar.SetSource(e.ChosenPhoto);
var b = new WriteableBitmap(imageVar.PixelWidth, imageVar.PixelHeight);
b.LoadJpeg(toStream(imageVar));//here comes the exception
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Stream toStream(BitmapImage img)
{
WriteableBitmap bmp = new WriteableBitmap((BitmapSource)img);
using (MemoryStream stream = new MemoryStream())
{
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
return stream;
}
}
Giving an error occurred when accessing the isolotedstorage. please help !
If I understand correctly, you are trying to:
Get image from a chooser (stream)
Create a bitmap object
Write it to another stream
Create a WriteableBitmap from that second stream
This is seriously convoluted. All you have to do is this:
var imageVar = new BitmapImage();
imageVar.SetSource(e.ChosenPhoto);
var b = new WriteableBitmap(imageVar.PixelWidth, imageVar.PixelHeight);
b.SetSource(e.ChosenPhoto);
This will get you the photo, but have in mind that if you first create a BitmapImage using the SetSource method, it will limit the size of your photo to be under 2000x2000. Then the WriteableBitmap will also be of that smaller, reduced size.
If you wish to create a full sized WriteableBitmap using LoadJpeg method, you need to do this:
//DO SOMETHING TO GET THE PIXEL WIDTH AND PIXEL HEIGHT OF PICTURE BASED JUST ON THE STREAM, FOR EXAMPLE USE EXIF READER: http://igrali.com/2011/11/01/reading-and-displaying-exif-photo-data-on-windows-phone/ OR SEE MORE ABOUT LOADING A LARGE PHOTO HERE: http://igrali.com/2012/01/03/how-to-open-and-work-with-large-photos-on-windows-phone/
var b = new WriteableBitmap(PixelWidth, PixelHeight);
b.LoadJpeg(e.ChosenPhoto);
That will load you the full sized JPEG.
The code you've used looks okay !
void photoChooser_Completed(object sender, PhotoResult e)
{
try
{
var imageVar = new BitmapImage();
imageVar.SetSource(e.ChosenPhoto);
var b = new WriteableBitmap(imageVar.PixelWidth, imageVar.PixelHeight);
b.LoadJpeg(toStream(imageVar));//here comes the exception
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Stream toStream(BitmapImage img)
{
WriteableBitmap bmp = new WriteableBitmap((BitmapSource)img);
using (MemoryStream stream = new MemoryStream())
{
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
return stream;
}
}
Try reconnecting USB !
You didnot specify, what you want to perform after fetching the Image.
If all you want is to display the image in your app, then you follow this code:
In your try block, simply add this
var imageVar = new BitmapImage();
imageVar.SetSource(e.ChosenPhoto);
Image img = new Image();
img.Source = imageVar;
this.ContentPanel.Children.Add(img);
because use zk upload component to upload a image,then insert the context path of the image to the CKEditor is too complex,
and at http://ckeditor.com/demo, you can see that CKEditor can upload image and flash etc,
but in zk, the CKEditor don't have this feature,
is that mean CKEditor in zk can't upload file?
I'm afraid this is not possible with zk.
I wrote a workaround to do this. You have to add a button to your GUI and add this EventListener to the button:
private class onUpload implements EventListener
{
#Override
public void onEvent(Event event) throws Exception
{
Media media = ((UploadEvent) event).getMedia();
if (media.getContentType().contains("image"))
{
reader.upload(media.getStreamData(), media.getName());
String description = edDescription.getValue();
description += "<img alt=\"\" src=\"/" + media.getName() + "\" />";
edDescription.setValue(description);
}
else
{
new Messagebox().show(_T("You can only upload images!"), _T("Not an image!"), Messagebox.OK, Messagebox.ERROR);
}
}
}
Reader is my class which handles file transfers and is used to write the data to the docroot. In my case the docroot of glassfish 3.1 can be located with the following code. I wrote the method getDocFolder() for ist because it also adds subfolders for each user if they don't already exists.
File file = new File("../docroot/");
This is the code for the upload method of the reader:
InputStream inputStream = null;
try
{
inputStream = new ByteArrayInputStream(imageStream);
String filename = getDocFolder()+"/"+imageName;
File file = new File(filename);
OutputStream out=new FileOutputStream(file);
byte buf[]=new byte[1024];
int len;
while((len = inputStream.read(buf)) > 0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (Exception ex)
{
Logger.getLogger(ImageReader.class.getName()).log(Level.SEVERE, "Error writing image", ex);
}
finally
{
try
{
inputStream.close();
}
catch (IOException ex) {}
}
I hope this helps
I'm using the Blackberry JDE (9000 simulator), and am wondering if I can display an image from the web.
Currently, I'm seeing tutorials that use Bitmap.getBitmapResource to display images that are local to the blackberry application, but looking at the API, I'm not seeing any support for giving a web URL.
Are there other Blackberry image classes I can check out? Or is this feature just not supported?
You can download image using HTTPConnection and InputStream, create EncodedImage from stream and then display it.
See coderholic - Blackberry WebBitmapField
BTW, you can use IOUtilities.streamToBytes() method to read bytes from InputStream directly!
Here is a code example for your problem:
HttpConnection httpConn = null;
InputStream inputStream = null;
int ResponseCode = HttpConnection.HTTP_OK;
byte[] ResponseData = null;
try {
httpConn = (HttpConnection) Connector.open(url, Connector.READ, true);
ResponseCode = httpConn.getResponseCode();
if (ResponseCode == HttpConnection.HTTP_OK) {
inputStream = httpConn.openInputStream();
ResponseData = IOUtilities.streamToBytes(inputStream);
}
}
catch(IOException e){
throw new IOException("HTTP response code: "
+ ResponseCode);
}
finally {
try {
inputStream.close();
inputStream = null;
httpConn.close();
httpConn = null;
}
catch(Exception e){}
}
return ResponseData;
If you want code that made to exactly do this (though this post is old, so I'm guessing you don't anymore)
Here