BitmapFactory.decodeFile() returning null xamarin.android - xamarin.android

When I am calling this function there is no image/string in _bitmap. In my application, I select image from the gallery and convert it to base64. I had debugged the app for the problem, so I found that the method BitmapFactory.decodeFile("image path") is returning null value even though the path which I am getting is totally fine.
private void _btnResimYolu_Click(object sender, System.EventArgs e)
{
var imageIntent = new Intent();
imageIntent.SetType("image/*");
imageIntent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(imageIntent, "Select Image"), 0);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
var imageView = FindViewById<ImageView>(Resource.Id.img1);
imageView.SetImageURI(data.Data);
_imageTest.Text = data.DataString;
}
}
private void _gonder_Click(object sender, System.EventArgs e)
{
string uriString = _imageTest.Text;
_bitmap = BitmapFactory.DecodeFile(uriString);
MemoryStream stream = new MemoryStream();
_bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
byte[] ba = stream.ToArray();
string bal = Base64.EncodeToString(ba, Base64.Default);
}

BitmapFactory.decodeFile() returning null
The problem is that your get the wrong image path, so the BitmapFactory.DecodeFile(uriString) always return null. The data.DataString in OnActivityResult is my device is :
[0:] data.Data = content://com.miui.gallery.open/raw/%2Fstorage%2Femulated%2F0%2FDCIM%2FCamera%2FIMG_20171125_143057.jpg
Solution :
When you choose a picture, you should convert its Uri to a real path. You could refer to my answer : How to get actual path from Uri xamarin android. Then, modify your code like this :
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == Result.Ok)
{
var uri = data.Data;
//You could find the GetActualPathFromFile() method code in the above link I have post.
string path = GetActualPathFromFile(uri);
_imageTest.Text = path ;
System.Diagnostics.Debug.WriteLine("data.Data = " + data.Data);
System.Diagnostics.Debug.WriteLine("path = " + path);
}
}
The image path :
[0:] path = /storage/emulated/0/DCIM/Camera/IMG_20171125_143057.jpg
Then you could BitmapFactory.DecodeFile() to implement your function.
Update :
Please make sure you have the WRITE_EXTERNAL_STORAGE permission, since Android 6.0, you have to Requesting Permissions at Run Time.

Related

Error executing: Java.Lang.Class[] parameterType = new Java.Lang.Class[] { Java.Lang.Class.FromType(typeof(sbyte[])) }; in Xamarin.Android

I'm trying to compile an android vector image in Xamarin Android based on a Java Sample but The system shows the following error:
{System.ArgumentException: type Parameter name: Type is not derived from a java type. at Java.Lang.Class.FromType (System.Type type) [0x00012] in the following part of the code:
Java.Lang.Class[] parameterType = new Java.Lang.Class[] { Java.Lang.Class.FromType(typeof(sbyte[])) };
Basically
private Drawable GetVectorDrawable(Context context, byte[] binXml)
{
try
{
// Get the binary XML parser (XmlBlock.Parser) and use it to create the drawable
// This is the equivalent of what AssetManager#getXml() does
// get the Class instance using forName method
var xmlBlock = Java.Lang.Class.ForName("android.content.res.XmlBlock");
System.Diagnostics.Debug.WriteLine(typeof(sbyte[]));
Java.Lang.Class[] parameterType = new Java.Lang.Class[] { Java.Lang.Class.FromType(typeof(sbyte[])) };
var xmlBlockConstr = xmlBlock.GetConstructor(parameterType);
//var xmlBlockConstr = xmlBlock.GetConstructor(Class.FromType(typeof(sbyte[])));
var xmlParserNew = xmlBlock.GetDeclaredMethod("newParser");
xmlBlockConstr.Accessible = true;
xmlParserNew.Accessible = true;
var parser = xmlParserNew.Invoke(xmlBlockConstr.NewInstance(binXml)) as XmlPullParser;
//System.Xml.XmlReader reader = parser.ToString();
//if (Build.VERSION.SdkInt >= (BuildVersionCodes)24)
//{
//ByteArray
//Drawable.CreateFromXml(context.Resources, reader);
//}
}
catch (System.Exception e)
{
}
return null;
}
This is the constructor I try to get:
public XmlBlock(byte[] data) {
mAssets = null;
mNative = nativeCreate(data, 0, data.length);
mStrings = new StringBlock(nativeGetStringBlock(mNative), false);
}
And this is the Java code I tried to traduce:
/**
* Create a vector drawable from a binary XML byte array.
* #param context Any context.
* #param binXml Byte array containing the binary XML.
* #return The vector drawable or null it couldn't be created.
*/
public static Drawable getVectorDrawable(#NonNull Context context, #NonNull byte[] binXml) {
try {
// Get the binary XML parser (XmlBlock.Parser) and use it to create the drawable
// This is the equivalent of what AssetManager#getXml() does
#SuppressLint("PrivateApi")
Class<?> xmlBlock = Class.forName("android.content.res.XmlBlock");
Constructor xmlBlockConstr = xmlBlock.getConstructor(byte[].class);
Method xmlParserNew = xmlBlock.getDeclaredMethod("newParser");
xmlBlockConstr.setAccessible(true);
xmlParserNew.setAccessible(true);
XmlPullParser parser = (XmlPullParser) xmlParserNew.invoke(
xmlBlockConstr.newInstance((Object) binXml));
if (Build.VERSION.SDK_INT >= 24) {
return Drawable.createFromXml(context.getResources(), parser);
} else {
// Before API 24, vector drawables aren't rendered correctly without compat lib
final AttributeSet attrs = Xml.asAttributeSet(parser);
int type = parser.next();
while (type != XmlPullParser.START_TAG) {
type = parser.next();
}
return VectorDrawableCompat.createFromXmlInner(context.getResources(), parser, attrs, null);
}
} catch (Exception e) {
Log.e(TAG, "Vector creation failed", e);
}
return null;
}
from this url: Given byte-array of VectorDrawable, how can I create an instance of VectorDrawable from it?
Can you help me?

Android Studio, downloading image form url/app has stopped working

Hi could you help me find out why my app stops working when I want to download image from url, here is the code
public void getOnClick(View view) throws IOException {
urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp- content/uploads/2010/11/Capri.jpg");
InputStream is = urlAdress.openStream();
filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
outputFile = new File(context.getCacheDir(),filename);
OutputStream os = new FileOutputStream(outputFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
is.close();
os.close();
I was also trying to use some code from similar topics but I get same message
Your app has stopped working
and it shuts down
Caused by: android.os.NetworkOnMainThreadException
The problem is that you are trying to download the image from the UIThread. You have to create a class which extends to AsyncTask class and make the download on the doInBackground method
private class DownloadAsync extends AsyncTask<Void, Void, Void> {
private Context context;
DownloadAsync(Context context) {
this.context = context;
}
#Override
protected Void doInBackground(Void... params) {
try {
URL urlAdress = urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp- content/uploads/2010/11/Capri.jpg");
InputStream is = urlAdress.openStream();
String filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
File outputFile = new File(context.getCacheDir(), filename);
OutputStream os = new FileOutputStream(outputFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
is.close();
os.close();
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Then you can execute like this
public void getOnClick(View view){
new DownloadAsync(this).execute();
}

navigating a image from page to other in mono android

I have an ImageView and Button in an Activity, lets call it A. When clicking on the Button, I start the image gallery, where I select an image and load that into the ImageView.
On the ImageView I subscribe to the Touch events, where I want to launch another Activity, B.
My question is, how can I in Activity B get the image, which was selected in Activity A? How is data passed fomr Activity to another Activity?
Here is my code in Activity A:
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
_imageView = FindViewById<ImageView>(Resource.Id.imageView1);
_imageView.Touch += TouchMeImageViewOnTouch;
Button button = FindViewById<Button>(Resource.Id.button1);
button.Click += ButtonOnClick;
}
private void ButtonOnClick(object sender, EventArgs eventArgs)
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
Uri uri = data.Data;
_imageView.SetImageURI(uri);
string path = GetPathToImage(uri);
Toast.MakeText(this, path, ToastLength.Long);
}
}
private string GetPathToImage(Uri uri)
{
string path = null;
string[] projection = new[] { Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
using (var cursor = ManagedQuery(uri, projection, null, null, null))
{
if (cursor != null)
{
int columnIndex = cursor.GetColumnIndexOrThrow(
Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
}
return path;
}
private void TouchMeImageViewOnTouch(object sender, View.TouchEventArgs touchEventArgs)
{
}
In your TouchMeImageViewOnTouch method, you will need to start Activity B. This is done by creating an Intent. This Intent can hold extra stuff the Activity you launch (B), will be able to get hold of.
So I see that you already found out how to get the path to the image, which you simply can pass along to Activity B in the Intent which is done like this:
private void TouchMeImageViewOnTouch(object sender, View.TouchEventArgs touchEventArgs)
{
var intent = new Intent(this, typeof (MainActivity));
intent.PutExtra("imagePath", path);
StartActivity(intent);
}
Then in Activity B you can get the path with:
Intent.GetStringExtra("imagePath");
Then do whatever you want with it.

Error while downloading & saving image to sd card in blackberry?

I am working on blackberry project where i want to download image & save it in sd card in blackberry. By going through many sites i got some code & based on that i wrote the program but when it is executed the output screen is displaying a blank page with out any response. The code i am following is..
code:
public class BitmapDemo extends UiApplication
{
public static void main(String[] args)
{
BitmapDemo app = new BitmapDemo();
app.enterEventDispatcher();
}
public BitmapDemo()
{
pushScreen(new BitmapDemoScreen());
}
static class BitmapDemoScreen extends MainScreen
{
private static final String LABEL_X = " x ";
BitmapDemoScreen()
{
//BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));
//add(bmpFld1);
setTitle("Bitmap Demo");
// method for saving image in sd card
copyFile();
// Add a menu item to display an animation in a popup screen
MenuItem showAnimation = new MenuItem(new StringProvider("Show Animation"), 0x230010, 0);
showAnimation.setCommand(new Command(new CommandHandler()
{
public void execute(ReadOnlyCommandMetadata metadata, Object context)
{
// Create an EncodedImage object to contain an animated
// gif resource.
EncodedImage encodedImage = EncodedImage.getEncodedImageResource("animation.gif");
// Create a BitmapField to contain the animation
BitmapField bitmapFieldAnimation = new BitmapField();
bitmapFieldAnimation.setImage(encodedImage);
// Push a popup screen containing the BitmapField onto the
// display stack.
UiApplication.getUiApplication().pushScreen(new BitmapDemoPopup(bitmapFieldAnimation));
}
}));
addMenuItem(showAnimation);
}
private static class BitmapDemoPopup extends PopupScreen
{
public BitmapDemoPopup(BitmapField bitmapField)
{
super(new VerticalFieldManager());
add(bitmapField);
}
protected boolean keyChar(char c, int status, int time)
{
if(c == Characters.ESCAPE)
{
close();
}
return super.keyChar(c, status, time);
}
}
}
public static Bitmap connectServerForImage(String url) {
System.out.println("image url is:"+url);
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url,Connector.READ_WRITE);
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
return hai.getBitmap();
} catch (Exception ex) {
System.out.println("URL Bitmap Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
public static void copyFile() {
// TODO Auto-generated method stub
EncodedImage encImage = EncodedImage.getEncodedImageResource("rim.png");
byte[] image = encImage.getData();
try {
// Create folder if not already created
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/");
if (!fc.exists())
fc.mkdir();
fc.close();
// Create file
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);
if (!fc.exists())
fc.create();
OutputStream outStream = fc.openOutputStream();
outStream.write(image);
outStream.close();
fc.close();
System.out.println("image saved.....");
} catch (Exception e) {
// TODO: handle exception
//System.out.println("exception is "+ e);
}
}
}
This is the code which i am using. Not getting any response except blank page.. As i am new to blackberry development unable to find out what is the problem with my code. Can anyone please help me with this...... Actually i am having other doubt as like android & iphone does in blackberry simulator supports for SD card otherwise we need to add any SD card slots for this externally...
Waiting for your reply.....
To simply download and save that image to the SDCard, you can use this code. I changed your SDCard path to use the pictures folder, which I think is the standard location on BlackBerrys. If you really want to store it in images, you may just need to create the folder if it doesn't already exist.
package com.mycompany;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
public class DownloadHelper implements Runnable {
private String _url;
public DownloadHelper(String url) {
_url = url;
}
public void run() {
HttpConnection connection = null;
OutputStream output = null;
InputStream input = null;
try {
// Open a HTTP connection to the webserver
connection = (HttpConnection) Connector.open(_url);
// Getting the response code will open the connection, send the request,
// and read the HTTP response headers. The headers are stored until requested.
if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
input = new DataInputStream(connection.openInputStream());
int len = (int) connection.getLength(); // Get the content length
if (len > 0) {
// Save the download as a local file, named the same as in the URL
String filename = _url.substring(_url.lastIndexOf('/') + 1);
FileConnection outputFile = (FileConnection) Connector.open("file:///SDCard/BlackBerry/pictures/" + filename,
Connector.READ_WRITE);
if (!outputFile.exists()) {
outputFile.create();
}
// This is probably not a robust check ...
if (len <= outputFile.availableSize()) {
output = outputFile.openDataOutputStream();
// We'll read and write this many bytes at a time until complete
int maxRead = 1024;
byte[] buffer = new byte[maxRead];
int bytesRead;
for (;;) {
bytesRead = input.read(buffer);
if (bytesRead <= 0) {
break;
}
output.write(buffer, 0, bytesRead);
}
output.close();
}
}
}
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (connection != null) {
connection.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
// do nothing
}
}
}
}
This class can download an image in the background, as I suggested. To use it, you can start a worker thread like this:
DownloadHelper downloader = new DownloadHelper("http://images03.olx.in/ui/3/20/99/45761199_1.jpg");
Thread worker = new Thread(downloader);
worker.start();
This will save the file as /SDCard/BlackBerry/pictures/45761199_1.jpg. I tested it on a 5.0 Storm simulator.
There are several problems with the code posted. It's also not completely clear what you're trying to do. From the question title, I assume you want to download a jpg image from the internet, and display it.
1) You implement a method called connectServerForImage() to download an image, but then it's commented out. So, the method isn't going to download anything if it's not called.
2) Even if it's uncommented, connectServerForImage() is called here
BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));
This will block the main (UI) thread while it downloads your image. Even though you can do it this way, it's not a good thing to do. Instead, you could create a Thread to download the image as a background task, and then use UiApplication.invokeLater() to load the image into your BitmapField on the main/UI thread.
3) Your copyFile() method tries to copy a file named rim.png, which must be an image bundled with your application, and saves it to the SDCard. Is this really what you want? Do you want to save the downloaded image instead? This method doesn't seem to be connected to anything else. It's not saving the image downloaded from the internet, and the image it does save is never used anywhere else.
4) In copyFile(), this line
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);
is passing a byte[] in as part of the filename to open (your variable named image). You should probably be adding a String name to the end of your SDCard path. As the code is, it's probably opening a file in the /SDCard/BlackBerry/images/ folder with a very long name that looks like a number. Or it might fail entirely, if there are limits on the length of filenames.
5) In Java, it's not usually a good idea to make everything static. Static should normally be used for constants, and for a very few methods like the main() method, which must be static.
Try to clean these things up, and then repost the code, and we can try to help you with your problem. Thanks.

Get bitmap from URI

I am selecting image from a gallery.
This is the code which i am using
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
this.StartActivityForResult(Intent.CreateChooser(intent,
"Select Picture"), SelectPicture);
I am getting this string in data.DataString content://media/external/images/media/11 on Activty result..
Which is not a full path to the selected Image. But ultimately i want to convert it to bitmap.
In activity result..
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
Bitmap bitmap = (Android.Graphics.Bitmap)data.Extras.Get("data");
Gives null error.
How ever instead of selecting image from the gallery when i capture image from camera it works fine and i get the bitmap. Code i am using:
var cameraIntent = new Intent(MediaStore.ActionImageCapture);
cameraIntent.PutExtra(MediaStore.ExtraOutput, imageUri);
this.StartActivityForResult(cameraIntent, TakePicture);
To convert from Uri to Bitmap follow this example: convertUriToBitmap.
In monodroid the code is as follows:
private Android.Graphics.Bitmap NGetBitmap(Android.Net.Uri uriImage)
{
Android.Graphics.Bitmap mBitmap = null;
mBitmap = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, uriImage);
return mBitmap;
}
Recipe:
http://docs.xamarin.com/android/recipes/Data/Files/Selecting_a_Gallery_Image
public override void OnActivityResult(int requestCode, int resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
Uri uri = data.Data;
}
Android
val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri))
Xamarin Android
var ins = context.ContentResolver.OpenInputStream(uri);
Bitmap bitamp = BitmapFactory.DecodeStream(ins);

Resources