I want to load a picture i have in the smartphone so i can than send it over the internet to a webservice i created.
Here i provide a sample code of what i am trying and not working.
Bitmap bm = BitmapFactory.decodeFile(path);
System.out.println("BITMAP: "+bm != null);
ByteArrayOutputStream buffer = new ByteArrayOutputStream(bm.getWidth() *bm.getHeight());
bm.compress(CompressFormat.JPEG, 100, buffer);
I made sure that bm isn't null with the system out print. I get a NullPointerException in ByteArrayOutputStream. Any suggestions?
Try this. Use file name with the path
String[] files = null;
File path = new File(Environment.getExternalStorageDirectory(),"folder path");
if(path.exists())
{
filename = path.list();
}
for(int i=0; i<count;i++)
{
Bitmap bitmapOrg = BitmapFactory.decodeFile(path.getPath()+"/"+ files[i]);
}
Related
I am trying to convert Java code into c#
So here is Java code
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap decodeStream = BitmapFactory.decodeStream(openInputStream, null, options);
Then I am saving this bitmap by
File appDirectory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File dest = new File(appDirectory, "yourImage.jpg");
try (FileOutputStream out = new FileOutputStream(dest)) {
decodeStream.compress(Bitmap.CompressFormat.JPEG, 100, out); // bmp is your Bitmap instance
} catch (IOException e) {
e.printStackTrace();
}
Now can anyone help me to convert this code into c#. I Tried to import Xamrine Android DLL but got success no far.
I am
As far as I understand you only need to load simple jpg image. That is all your java code do.
If you want to load jpg image from stream you can use
Bitmap.FromStream()
e.g.
using (FileStream fs = new FileStream(#"Image Address.jpg", FileMode.Open, FileAccess.Read))
{
var decodeStream = Bitmap.FromStream(fs);
}
of course you can open your image without stream too.
var image = Bitmap.FromFile(#"Image Address.jpg");
So your code will be something like this
File appDirectory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File dest = new File(appDirectory, "yourImage.jpg");
var image = Bitmap.FromFile(dest.FullName);
You can not access Bitmap class out of the box.
For dot net core install package System.Drawing.Common.
For dot net framework add reference to System.Drawing.
For Xamarin see this answer https://stackoverflow.com/a/34869330/5964792
How to compress jpg/bmp files which I can store in the memory then when needed decompress those images and show to users without losing too much of image quality? How to do the compress and decompress, any guidance/ link would be helpful.
Thank you
create image thumbnails
'byte[] imageData = null;
try
{
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(fileName);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
}
catch(Exception ex) {
}`
if u need for thumbNail then use
ThumbNailUtils.extractThumbnail(Bitmap source,int width,int height)
it show thumbnail from bitmap and when u want to show original bitmap then show bitmap
.
use wisely bitmap object cause it take more memory at runtime.
how to update image showing in imageView
i set this image from database
code to get image on imageView from db is...
InputStream is = resultSet.getBinaryStream("image");
OutputStream os;
os = new FileOutputStream(new File("src/sources/images/photo.jpg"));
byte[]content = new byte[1024];
int size = 0;
while((size=is.read(content))!= -1)
{
os.write(content,0,size);
}
os.close();
is.close();
image = new Image("file:src/sources/images/photo.jpg");
imageView.setImage(image);
image is saving in BLOB type in MySQL database
Now i want to update this image and set it again this image if i dont choose any image using file chooser
please solve my this problem
thanks in advance
File chooser code
stage = (Stage) showScene.getScene().getWindow();
file = fileChooser.showOpenDialog(stage);
if(file != null){
image = new Image(file.getAbsoluteFile().toURI().toString(),imageView.getFitWidth(),imageView.getFitHeight(),true,true);
imageView.setImage(image);
imageView.setPreserveRatio(true);
}
fis = new FileInputStream(file); // here i got error(null pointer exception) if i try to update withouting choosing image from filechooser
I pass fis to the preparedstatement to update and also insert
You are getting a NullPointerException because if you don't choose a file with the FileChooser, your file variable is set to null. This can be resolved by altering your if statement a little.
file = fileChooser.showOpenDialog(stage);
if (file == null) {
file = new File("path/to/default/file")
}
image = new Image(file.getAbsoluteFile().toURI().toString(),imageView.getFitWidth(),imageView.getFitHeight(),true,true);
imageView.setImage(image);
imageView.setPreserveRatio(true);
fis = new FileInputStream(file);
I am trying to get image from gallery. It is giving me image as bitmap. I want the image in .jpg file so that I can save file name in my database.
I have followed this tutorial :
http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample
gallery image selected code:
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
File file = new File(picturePath);// error line
mProfileImage = file;
profile_image.setImageBitmap(bm);
}
I tried this. But I am getting null pointer on file.
Exception :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
Also I don't want this newly created file to be saved in external storage. This should be a temporary file. How can I do this?
Thank you..
The good news is you're a lot closer to done than you think!
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
At this point, if bm != null, you have a Bitmap object. Bitmap is Android's generic image object that's ready to go. It's actually probably in .jpg format already, so you just have to write it to a file. you want to write it to a temporary file, so I'd do something like this:
File outputDir = context.getCacheDir(); // Activity context
File outputFile = File.createTempFile("prefix", "extension", outputDir); // follow the API for createTempFile
Regardless, at this point it's pretty easy to write a Bitmap to a file.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream); //replace 100 with desired quality percentage.
byte[] byteArray = stream.toByteArray();
Now you have a byte array. I'll leave writing that to a file to you.
If you want the temporary file to go away, see here for more info: https://developer.android.com/reference/java/io/File.html#deleteOnExit()
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
if (bm != null) { // sanity check
File outputDir = context.getCacheDir(); // Activity context
File outputFile = File.createTempFile("image", "jpg", outputDir); // follow the API for createTempFile
FileOutputStream stream = new FileOutputStream (outputFile, false); // Add false here so we don't append an image to another image. That would be weird.
// This line actually writes a bitmap to the stream. If you use a ByteArrayOutputStream, you end up with a byte array. If you use a FileOutputStream, you end up with a file.
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.close(); // cleanup
}
I hope that helps!
Looks like your picturePath is null. That is why you cannot convert the image. Try adding this code fragment to get the path of the selected image:
private String getRealPathFromURI(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
After that, you need to modify your onSelectFromGalleryResult. Remove/disable line String[] filePath = {MediaStore.Images.Media.DATA}; and so on and replace with below.
Uri selectedImageUri = Uri.parse(selectedImage);
String photoPath = getRealPathFromURI(selectedImageUri);
mProfileImage = new File(photoPath);
//check if you get something like this - file:///mnt/sdcard/yourselectedimage.png
Log.i("FilePath", mProfileImage.getAbsolutePath)
if(mProfileImage.isExist()){
//Check if the file is exist.
//Do something here (display the image using imageView/ convert the image into string)
}
Question: What is the reason you need to convert it in .jpg format? Can it be .gif, .png etc?
I am trying to open an image I have stored on external memory. Here is the code I have:
File imagePath = new File(imageURI);
InputStream inputStream=null;
try {
inputStream = getContentResolver().openInputStream(Uri.parse(imageURI));
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] originalImage = baos.toByteArray();
But it doesn't seem to be able to locate the file. The Uri is in the format content://com.android.providers.media.documents/document/image%3A21.
Thanks for any help.
In a project I am working on now I have external images in a directory on the SD card. I am using
String thePath = Environment.getExternalStorageDirectory() + "/myAppFiles”;
File imgFile = new File(thePath + " / " + "
externalImage.jpg ");
if (imgFile.exists()) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 6;
Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
}
}
Try this:
File imagePath = new File(imageURI.getPath());
url.getPath() returns a String in the following format: "/mnt/sdcard/xxx.jpg", without the scheme type pre-fixed