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);
Related
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.
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.
I am trying to display a PNG image on blackberry device for OS 5.0 using J2ME MIDlet class instead of a blackberry RIMlet class. Can I use J2ME MIDlet instead of RIMlets? Would it be compatible with blackberry as blackberry do support J2ME? Can I get the image from it?
To display an image on the screen of a BlackBerry® device, create an Image object and populate it by calling the static Image.createImage() method. Provide the location of the image as a parameter.
refer display an PNG image using J2ME MIDlet classes on blackberry device
Can i use J2ME MIDlet instead of RIMlets...
YES, but there are certain advantages like mentioned here.
and if you want to go with MIDlet, here is an example using ImageItem,
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class ImageItemMIDlet extends MIDlet implements CommandListener{
private Command exit;
private ImageItem imageItem;
private Image image;
private Display display;
private Form form;
public ImageItemMIDlet(){
try{
image = Image.createImage("/yourImage.png");
} catch (Exception e){ }
imageItem = new ImageItem("This is the IMAGE_ITEM Application",
image, ImageItem.LAYOUT_DEFAULT, "image");
}
public void startApp(){
form = new Form("ImageItem Example");
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
form.append(imageItem);
form.addCommand(exit);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){
notifyDestroyed();
}
public void commandAction(Command c, Displayable d){
String label = c.getLabel();
if(label.equals("Exit")){
destroyApp(true);
}
}
}
public class Midlet extends MIDlet {
public Display display;
public void startApp() {
Canvas obj = new DrawImage();
display = Display.getDisplay(this);
display.setCurrent(obj);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public class DrawImage extends Canvas{
int width = getWidth();
int height = getHeight();
protected void paint(Graphics g) {
try {
System.out.println("111111");
Image image = Image.createImage("/Waterfall.png");
if(image != null)
g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
else
System.out.println("2222");
} catch (IOException ex) {
System.out.println(ex);
}
}
}
}
Its good to use Midlet with canvas to show on canvas because if you use Midlet with Form then its show image but its also showing the theme of mobile in background of form. If you use canvas you can use also background image for your front image.
Thanks
my code are as follows
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
Stream stream = e.ChosenPhoto;
int len = (int)stream.Length;
byte[] PhoteBytes = new byte[len];
stream.Read(PhoteBytes,0,len);
}
}
I am wondering is it possible to convert
byte array(PhoteBytes in this example)
to WriteableBitmap?
Thanks for the help
Try this.
WritableBitmap bitmap = new WritableBitmap(); //Use appropriate constructor
bitmap.SetSource(e.ChosenPhoto);
EDIT: You'll have to use the appropriate constructor. In one WriteableBitmap(Int32, Int32) constructor you can specify the bitmap width and height. See documentation here
I want to implement an Android file chooser for OCR.
I have the source code from this site: here
What I want is to create a main Activity using an intent to call the FileChooser
public class MainFileChooser extends Activity {
Button btnBrowse =null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.utama);
btnBrowse = (Button)findViewById(R.id.btnBrowse);
btnBrowse.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(MainFileChooser.this, FileChooser.class);
startActivity(intent);
}
});
}
}
While the button is clicked it will be linked to FileChooser and then while a tile is clicked the activity will be returned toMainFileChooser and also return the file path.
The File Path will be processed for OCR such as converting to gray scale, features extraction and so on.
The Question is how can I return the image path to MainFileChooser activity and for the given path I can create bitmap image (buffered image)?
Like the source code for FileChooser suggested, you can modify onFileClick to return the image path:
private void onFileClick(Option o) {
String path = o.getName();
Intent data = new Intent();
data.putExtra("path", path);
setResult(Activity.RESULT_OK, data);
finish();
}
Then, in MainFileChooser, instead of startActivity, use startActivityForResult:
setActivityForResult(intent, 1234);
You will also need to add onActivityResult to MainFileChooser to get the filename:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 1234) {
String path = data.getStringExtra("path");
Toast.makeText(this, "Path: " + path, Toast.LENGTH_SHORT).show();
}
}