Issues with initiating 9-patch drawables from input resources - android

Having kind of an issue with initiating 9patch drawables from input streams. I need to skin my app and need to download skin elements and images from a web service.
Sought through a reasonable amount of resources both in SO and android dev guides, but none seem to work for me.
Setting a drawable from a resource does handle 9patch properly so logically the smarts to do so is there, but for some reason the following code, which I derived from the android sources itself, fails to handle 9patch properly
Rect pad = new Rect();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScreenDensity = DisplayMetrics.DENSITY_DEFAULT;
Bitmap bm = BitmapFactory.decodeResourceStream(resources, typedValue, new FileInputStream(path), pad, opts);
if (bm != null) {
byte[] np = bm.getNinePatchChunk();
if (np == null || !NinePatch.isNinePatchChunk(np)) {
np = null;
pad = null;
}
if (np != null) {
drawable = new NinePatchDrawable(resources, bm, np, pad, path);
} else {
drawable = new BitmapDrawable(resources, bm);
}
}
I have changed the input source to be the one of my files (FileInputStream(path)), in the android sources it is the input source initiated on resource images.
This code always returns BitmapDrawable even if the input image is a 9-patch.
Does anyone succeed actually getting this functionality working?
I'd appreciate any help or hint towards a solution.
Thank you in advance.

Okay, the solution is that there's no solution here, because 9 patch requires nine patch chunk as an array which is being generated at compile time. Obviously we do not have a compile phase when loading images from a web resource.
To Android engineers - maybe future release of android SDKs will be able to generate the nine patch chunk at run time.

I've created this gist to create 9patches at runtime: https://gist.github.com/4391807

Related

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 gradients with banding artifact

I am having a problem with Android graphics. I am doing game development and need to display images some of which have color gradients. My problem is that when I load bitmap images (in png format) with gradients the images display with a banding artifact. And this is on Android 4. I researched numerous posts relating to this issue, and tried numerous solutions including:
Dithering the image on input
BitmapFactory.Options factoryOptions =
new BitmapFactory.Options();
factoryOptions.inDither = true;
...
background = BitmapFactory.decodeResource( resources, R.drawable.game_page_background, factoryOptions );
Loading the image from "res/raw" instead of "res/drawable"
Verifying the pixel format of my display as: Bitmap Config ARGB_8888
Loading the image from the assets directory using an input stream.
I assumed Solutions 2 and 4 should have prevented Android image "optimization" which (again I assume) is producing the artifact. But none of the solutions work. The artifact remains no matter how I load the bitmap. In the end I had to do a horrible workaround which was to bake noise into the image using photoshop. Obviously, this is a horrible workaround.
Can anyone from this community offer any further advice as to how to get bitmap images with gradients to render smoothly in Android without the banding artifact?
The following code frags show how I've generated these test images...
CODE FRAG **
...
InputStream is = null;
try
{
is = ((Activity)gameMngr).getAssets().open("test_background_3.png");
}
catch( IOException ioe)
{
Log.d(TAG, "TEST CODE: Unable to open resources. ");
}
this.background = BitmapFactory.decodeStream(is);
...
// ELSEWHERE
...
canvas.drawBitmap( this.background, 0, 0, null );
...
END FRAG **
I think you can create a copy of your from decodeStream and specify the Bitmap COnfig
Here is the revised code frag of yours:
InputStream is = null;
try
{
is = ((Activity)gameMngr).getAssets().open("test_background_3.png");
}
catch( IOException ioe)
{
Log.d(TAG, "TEST CODE: Unable to open resources. ");
}
this.background = BitmapFactory.decodeStream(is);
//create copy and specify the config of the bitmap, setting to true make the bitmap
//mutable.
Bitmap newBtmp = this.background.copy(Bitmap.Config.ARGB_8888, true);
//use the newBtmp object
canvas.drawBitmap( newBtmp, 0, 0, null );
...
If this post helps you, please make this post as an answer.
Thanks.

Android Bytes to Bitmap

I have this working just fine in our iPhone app, but am having problems in Android. I'm using the same urls/data in both apps. When I set my image in my ListView to the bitmap that came from the bytes, the image doesn't appear. The data is there. Here is the code where I assign the view:
if (camera.snapshot != null)
{
bMap = BitmapFactory.decodeByteArray(camera.snapshot, 0, camera.snapshot.length);
image.setImageBitmap(bMap);
}
This is where I convert the string data into bytes:
camera.snapshot = responseData.getBytes();
The images are PNG files. They come in about 4 times the size that I need them for the listview image but I would think they would size perfectly to the bounds I set the ImageView to be.
On iPhone I simply use NSData and then use a prebuilt method in ImageView to turn it into an image. It works perfectly! What am I missing here?
You probably need to use the 4-argument version of decodeByteArray: see http://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeByteArray%28byte[],%20int,%20int,%20android.graphics.BitmapFactory.Options%29.
The options would depend on the type of PNG image, so that you might need to experiment with. For a generic PNG, maybe something like this?
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inDither = true;
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
You can see http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html and http://developer.android.com/reference/android/graphics/Bitmap.Config.html for more detail.
Everything is fine here. So you need to debug to try and find where else is the issue. i.e. is Camera.snapshot = null ? i.e. you might not be getting the data properly. Or there could also be an issue in the layouts to show the imageview. Try setting a predefined image to imageview and see if it is shown. This way you would be able to track the problem.

Android Live Wallpaper guidance

When it comes to making Android live wallpaper, what are the things that are exactly needed. So far I could gist as WallpaperService.Engine, SurfaceView, some major changes in Android.manifest and xml/string.xml apart from this one png drawble (i think this may be optional if i use paint).
And what else do I need to develop whole different logic for the animation to happen? is it with mathematical calculations always? I am very keen about making different kind of live wallpaper. but i am not in the right track i think.
Please suggest me some way out to right direction summarizing me what all i need so that i can make any kind of live wallpaper.
Can somebody please summarize what all is needed for live wall paper.
Thanks in Advance.
Hi you can use this code if You have Image path.
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
Bitmap useThisBitmap = Bitmap.createScaledBitmap(
bitmap, parent.getWidth(), parent.getHeight(), true);
bitmap.recycle();
if(imagePath!=null){
System.out.println("Hi I am try to open Bit map");
wallpaperManager = WallpaperManager.getInstance(this);
wallpaperDrawable = wallpaperManager.getDrawable();
wallpaperManager.setBitmap(useThisBitmap);
................................................. if you have image URI then use this
wallpaperManager = WallpaperManager.getInstance(this);
wallpaperDrawable = wallpaperManager.getDrawable();
mImageView.setImageURI(imagepath);
.............. Let me know if there is any issue .
Yes, you need to use a different approach for live wallpaper than "normal" animation in Android. The standard approach is to make a self-rescheduling runnable that draws to canvas.
In answer to one of your specific questions: no, you do not need to limit yourself to mathematical calculations; you can use bitmaps/sprites if you choose, but you will need to animate them yourself.
Your best place to start is the resources in the SDK:
http://developer.android.com/resources/articles/live-wallpapers.html
http://developer.android.com/resources/samples/CubeLiveWallpaper/index.html

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