JPG image shows from phone but not from server - android - android

In my app I am able to pick up a picture from the Gallery and show it on my phone. The picture has extension JPG. But when I email it to myself, save it on the server and then try to display it on my phone, it does not display. I even tried to downsize it to 30% using my email app on the phone, so now it is 220KB instead of 1.4MB but it still does not display.
In both cases I use the method
imageView.setImageBitmap(BitmapFactory.decodeFile(personPicture))
What do I need to do to overcome this problem?
BTW: the name of the picture was changed when I saved it on the server. I do not think it matters but I mentioned it anyway.
EDIT
The above is all the code I am using. Just to complete the issue here is the code that handles both jpg and png and it works if the picture is renamed to png.
if (url.contains("jpg")) {
imageView.setImageBitmap(BitmapFactory.decodeFile(url));
} else {
Drawable drw = LoadImageFromWebOperations(url);
if (drw != null) {
imageView.setImageDrawable(drw);
}
}
Note: the 1.4MB PNG file worked fine on the emulator but gave Out of memory exception on the device. When I re-sized the PNG file to 350KB it displayed properly on the device also.
If needed here is the url used in the above code (a picture of a cat)/
http://212.150.56.58:8080/feedback/pictures/56.png

When you try to load image from server into app, load it using Picasso library like as below:
Picasso.with(MainActivity.this).load("image_to_be_loaded").into(profile_image);
Edit
If you don't want to use third party library then try the following code:
public Drawable loadImageFromURL(String url, String name) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, name);
return d;
} catch (Exception e) {
return null;
}
}

Use Picasso to load server images to your app image view it also supports caching and lot many features.
Use is like this
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
checkout Picasso Library for more details.

I do not understand why, but if I renamed the picture on my server to extension PNG the picture displays, in all sizes.

Related

How To Get Clear Image From FaceBook

I used graph API Json Response of Facebook Wall Post Images and display in my APP i successfully got it. But the wall images look very Blur how to resolve? i used this code for get wall picture
URL url=new URL(hashMap.get("picture_url"));
bitmap=BitmapFactory.decodeStream(url.openConnection().getInputStream());
((ImageView)view.findViewById(R.id.imageView_FullImage)).setImageBitmap(bitmap)
The Facebook Graph API as well as the FQL data set always returns the Picture URL of a thumbnail. If you look at the URL it returns, it will have one of these ending (right before the image extension .jpg, .png, etc) _t., _a.. For example, if the URL is to a JPG file, it could have an ending _t.jpg
The idea is to swap the ending and choose a normal size for the image that is returned. To do this, use the code below that will replace the endings with the one for normal sized images (that should have the _n.)
By the way, I don't think the tag you are looking for is picture_url. It should be just picture. But regardless, get the source URL as shown below, replace the endings and then pass it to the this line in your code:
// THIS SHOULD BE AFTER THE if....else code block
bitmap=BitmapFactory.decodeStream(url.openConnection().getInputStream());
CODE TO REPLACE THE VARIOUS THUMBNAIL IMAGES: By the way, this is production code and works perfect.
String PICTURE_URL;
String getPicture = JOFeeds.getString("picture");
if (getPicture.contains("_t.")) {
PICTURE_URL = getPicture.replaceAll("_t.", "_n.");
} else if (getPicture.contains("_a.")) {
PICTURE_URL = getPicture.replaceAll("_a.", "_n.");
} else if (getPicture.contains("_s.")) {
PICTURE_URL = getPicture.replaceAll("_s.", "_n.");
} else if (getPicture.contains("_q.")) {
PICTURE_URL = getPicture.replaceAll("_q.", "_n.");
}
Note: However, in some cases, like a Video preview or a Link preview, it will not always have a bigger image available. Nothing much you can do about it nor can Facebook I suspect. These typically come from posts that are shared by users from other websites.

(Beginner) How do I automatically load images off of a website into an imageview

I'm building an app for a friends funny pictures website. I downloaded the gridview activity from the android developers website, but it just loads preset image urls, and that's simply not going to work for us. We need an image loader that can automatically load images from the site.
Any help would be greatly appreciated.
Use lazylist download
https://github.com/thest1/LazyList
Lazy load of images in ListView
Hope AQuery library is what you are looking for easy image loading on ImageView
Try out this
Drawable drawable = LoadImage(<Replace this with your url> + UserProfile.Photo);
UserPhotoImageView.setImageDrawable(drawable);
<replace with Your Image View>.setImageDrawable(drawable);
public Drawable LoadImage(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e)
{
System.out.println("Exc=" + e);
return null;
}
}
Rather than what others are suggesting, I think the best way to do this is use a UniversalImageLoader. It will allow you to Lazy Load, and cache on the SD card and internal storage. In short, it makes things simpler and allows you to get the fastest speed possible. Try it out.

High resolution screen shot in Android

Is there any way to get a high resolution screen shot of a certain view in an activity.
I want to convert html content of my webview to PDF. For that I tried to take screen shot of the webview content and then converted it to PDF using itext. The resulted PDF is not in much more clarity.
My code:
protected void takeimg() {
Picture picture = mWebView.capturePicture();
Bitmap b = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
// byte[] bt = b.getNinePatchChunk();
// Bitmap b;
// View v1 = mWebView.getRootView();
// v1.setDrawingCacheEnabled(true);
// b = Bitmap.createBitmap(v1.getDrawingCache());
// v1.setDrawingCacheEnabled(false);
FileOutputStream fos = null;
try {
File root = new File(Environment.getExternalStorageDirectory(),
"Sample");
if (!root.exists()) {
root.mkdir();
}
String sdcardhtmlpath = root.getPath().toString() + "/"
+ "temp_1.png";
fos = new FileOutputStream(sdcardhtmlpath);
// fos = openFileOutput("samsp_1.jpg", MODE_WORLD_WRITEABLE);
if (fos != null) {
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
// fos.write(bt);
fos.close();
}
} catch (Exception e) {
Log.e("takeimg", e.toString());
e.printStackTrace();
}
}
protected void pdfimg() {
Document mydoc = new Document(PageSize.A3);
try {
File root = new File(Environment.getExternalStorageDirectory(),
"Sample");
if (!root.exists()) {
root.mkdir();
}
String sdcardhtmlpath = root.getPath().toString() + "/";
mydoc.setMargins(0, 0, 0, 0);
PdfWriter.getInstance(mydoc, new FileOutputStream(sdcardhtmlpath
+ PDFfilename));
mydoc.open();
Image image1 = Image.getInstance(sdcardhtmlpath + "temp_1.jpg");
image1.scalePercent(95f);
mydoc.add(image1);
// mydoc.newPage();
mydoc.close();
} catch (Exception e) {
Log.e("pdi name", e.toString());
}
}
Update: See Edit 3 for an answer to op's original question
There are two options:
Use a library to convert the HTML to PDF. This is by far the best option, since it will (probably) preserve text as vectors.
Get a high resolution render of the HTML and save it as a PNG (not PDF surely!).
For HTML to PDF, wkhtmltopdf looks like a good option, but it relies on Qt which you can't really use on Android. There are some other libraries but I doubt they do the PDF rendering very well.
For getting a high-res webview, you could try creating your own WebView and calling onMeasure(...) and onLayout(...) and pass appropriate parameters so the view is really big. Then call onDraw(myOwnCanvas) and the webview will draw itself to your canvas, which can be backed by a Bitmap using Canvas.setBitmap().
You can probably copy the state into the new WebView using something like
screenshotterWebview.onRestoreInstanceState(mWebView.onSaveInstanceState());
Orrr it may even be possible to use the same WebView, just temporarily resize it to be large, onDraw() it to your canvas, and resize it back again. That's getting very hacky though!
You might run into memory issues if you make it too big.
Edit 1
I thought of a third, exactly-what-you-want option, but it's kind of hardcore. You can create a custom Canvas, that writes to a PDF. In fact, it is almost easy, because underlying Canvas is Skia, which actually includes a PDF backend. Unfortunately you don't get access to it on Android, so you'll basically have to build your own copy of it on Android (there are instructions), and duplicate/override all the Canvas methods to point to your Skia instead of Androids. Note that there is a tempting Picture.writeToStream() method which serializes the Skia data, but unfortunately this format is not forwards or backwards compatible so if you use it your code will probably only work on a few versions of Android.
I'll update if/when I have fully working code.
Edit 2
Actually it is impossible to make your own "intercepting" Canvas. I started doing it and went through the tedious process of serializing all function calls. A few you can't do because they are hidden, but those didn't look important. But right at the end I came to serializing Path only to discover that it is write-only. That seems like a killer to me, so the only option is to interpret the result of Picture.writeToStream(). Fortunately there are only two versions of that format in use, and they are nearly identical.
Edit 3 - Really simple way to get a high resolution Bitmap of a view
Ok, it turns out just getting a high res bitmap of a view (which can be the entire app) is trivial. Here is how to get double resolution. Obviously all the bitmaps look a bit crap, but the text is rendered at full resolution:
View window = activity.getWindow().getDecorView()
Canvas bitmapCanvas = new Canvas();
Bitmap bitmap = Bitmap.createBitmap(window.getWidth()*2, window.getHeight()*2, Bitmap.Config.ARGB_8888);
bitmapCanvas.setBitmap(bitmap);
bitmapCanvas.scale(2.0f, 2.0f);
window.draw(bitmapCanvas);
bitmap.compress(Bitmap.CompressFormat.PNG, 0, myOutputStream);
Works like a charm. I've now given up on getting a PDF screenshot with vector text. It's certainly possible, but very difficult. Instead I am working on getting a high-res PSD where each draw operation is a separate layer, which should be much easier.
Edit 4
Woa this is getting a bit long, but success! I've generated an .xcf (GIMP) and PDF where each layer is a different canvas drawing operation. It's not quite as fine-grained as I was expecting, but still, pretty useful!
Actually my code just outputs full-size PNGs and I used "Open as layers..." and "Autocrop layer" in GIMP to make these files, but of course you can do that in code if you like. I think I will turn this into a blog post.
Download the GIMP or Photoshop demo file (rendered at 3x resolution).
When you capture the view, just screen bound will capture ( due to control weight and android render pipeline ).
Capturing screenshot for converting to PDF is tricky way. I think two way is more reasonable solutions.
Solution #1
Write a parser ( it's simple ) to convert webview content ( that is HTML ) to iText format.
You can refer to this article for more information.
http://www.vogella.com/articles/JavaPDF/article.html
Also to write a parser you can use REGEX and provide your own methods like parseTable, parseImage, ...
Solution #2 Internet Required
Provide a URL ( or webservice ) to convert HTML to PDF using PHP or C# that has a lot of nice libraries. Next you can send download link to the Client ( Android Device ).
So you can also dynamically add some Tags, Banners, ... to the PDF from server side.
Screen Shot is nothing but picture of your device display which usually depend upon your phone absolute pixels, if your phone is 480x800 screen shot will be same and generally applicable for all scenarios.
Sure, Use this:
Bitmap bitmap;
View v1 = MyView.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
Here MyView is the View you need a screenshot of.

Android: Getting Drawable from URL not working for .jpg, only works for .png

I am working on and Android app that pulls a picture from an internet page (specifically xckd.com). I have it working wonderfully using code of this basic form (see below)
ImageView iv = new ImageView;
URL url = new URL(address);
InputStream content = (InputStream)url.getContent();
Drawable d = Drawable.createFromStream(content , "src");
iv.setImageDrawable(d)
I noticed when I was viewing some of their older comics the image would not show (but I was scraping the other information from the page properly so I know the url is correct). I determined that this result only occurs when the image is a .jpg file but works perfectly when it is a .png
I have Googled around plenty and I can't figure out why this is, is there a simple fix for this?
It's a known issue http://code.google.com/p/android/issues/detail?id=6066. Using FlushedInputStream solves it.

Can BitmapFactory.decodeFile handle .ICO (Windows icons) files?

I am working on Android. Trying to display the "favicon" (aka "shortcut icon") or web pages.
So I already have the code to get the URL of this icon from any website, and download it onto my Android.
Now I am trying to make a Bitmap out of it, but always get null as a result.
The code:
String src = String.format("file:///data/data/com.intuitiveui.android/files/%s",prefName);
// prefName is "facebook.ico", and I do see tht file in my DDMS file browser. It's
// a valid icon file.
Bitmap res = BitmapFactory.decodeFile(src);
// This returns null
TIA
Here is a list of the supported Android media formats. ICO is not among them. You might be able to find a Java-based ICO decoder, though.
SKIA library provides decoder class for ICO file. I was able to display an ICO file in the emulator. Haven't tried it yet in an actual android device though.
Bitmap bmap = BitmapFactory.decodeFile("/sdcard/vlc.ico");
I had a similar problem. BitmapFactory.decode decoded *.ico on emulator but not on my Galaxy S. Solution for me was:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read=0;
while((read = inputStream.read()) != -1){
bos.write(read);
}
byte[] ba = bos.toByteArray();
Bitmap icon = BitmapFactory.decodeByteArray(ba, 0, ba.length);//new FlushedInputStream(inputStream));
The WebView component has a getFavicon() method so it's definitely possible to decode ICO files in Android. You could have a look at the Android source to see how ICO files are parsed. I've had a quick look but can't find the relevant part.
Alternatively, you should be use the SDK to get favicons for you. However, I've had a quick try and can't get it to work.
For what it's worth here's my test code, noting again that this doesn't work:
String url = "http://stackoverflow.com";
WebView wv = new WebView(this);
wv.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
Log.i("HelloAndroid","Loaded " + url);
Log.i("HelloAndroid","Icon " + (view.getFavicon() == null ? "not" : "") + " found");
}
});
WebIconDatabase wid = WebIconDatabase.getInstance();
wid.requestIconForPageUrl(url, new WebIconDatabase.IconListener() {
public void onReceivedIcon(String url, Bitmap icon) {
Log.i("HelloAndroid","Found Icon for " + url);
}
});
wv.loadUrl("http://stackoverflow.com");
Log.i("HelloAndroid","Loading " + url);
The problem may be down to the fact that I'm not adding the WebView to a visible View. If you do get this to work I'd be interested to hear what you did.
So sorry for giving two half complete answers, but I thought it was worth posting what I found.
No accepted answer util now, I will share my findings here.
Windows .ico file format is a little complicated, it might contains one or more small images at multiple sizes and color depths, such that they may be scaled appropriately. Refer ICO_(file_format)
So when using unix "file" command to check the icon file type, you might get the following result:
a.ico : MS Windows icon resource - 1 icon, 32x32
b.ico : MS Windows icon resource - 9 icons, 256x256
Note a.ico and b.ico contains different number of icons.
I tried to use BitmapFactory.decodeFile to decode these icons.
Two Android devices with Android 4.3 can only decode a.ico, but can not decode b.ico.
Devices with Android 4.4 or later can decode both a.ico and b.ico.
As I only have limited Android devices, I can't give any conclusion. Maybe anyone else could help.
So if you really want to decode .ico files, you may try:
Create .ico files with only 1 image/picture in it
Write your own .ico decoder or 3rd library like image4j
I was also stuck with this since Picasso didn't seem to parse .ico files.
Surprisingly however, the solution is fairly simple.
InputStream in = new java.net.URL("https://" + domain + "/favicon.ico").openStream();
Bitmap b = BitmapFactory.decodeStream(in);
For me, this solution works with most of the websites but produces an empty bitmap whenever the size of the icon file is exceptionally low.

Categories

Resources