i am trying to add a thumbnail dynamically to my relative layout. This is code here
public void showViewOfReceipt(String fileName)
{
byte[] imageData = null;
try
{
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(fileName);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
Float width = new Float(imageBitmap.getWidth());
Float height = new Float(imageBitmap.getHeight());
Float ratio = width/height;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, (int)(THUMBNAIL_SIZE * ratio), THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
ImageView image = new ImageView(this);
image.setImageBitmap(imageBitmap);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.expLayout5);
layout.addView(image);
}
catch(Exception ex) {
}
}
It never shows anything
Regards
Change your following line of code,
catch(Exception ex)
{
}
to,
catch(Exception ex)
{
e.printStack();
}
So, you will get error , if any.
1- Change your relative layout to Linear Layout
2- Use this code below to get the bitmap image
Uri photoUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
if (cursor.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap imageReturned = BitmapFactory.decodeFile(filePath);
showImageInLayout(imageReturned);
Then define a function showImageInLayout(Bitmap imageReturned)
public void showViewOfReceiptInLayout(Bitmap imageBitmap)
{
byte[] imageData = null;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, yourWidth, yourHeight, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
ImageView image = new ImageView(this);
image.setImageBitmap(imageBitmap);
layout.addView(image);
}
Comment code line:
//image = (ImageView) findViewById(R.id.imageView1);
Please update the Question with the error or exception log code so we can help you properly.
And as per Altaaf answer its an error in the fileName. So Please check it or give the code what you pass in it.
Thanks.
Related
I am trying to take a screenshot of my Augmented Reality Screen and pass it as a bitmap to another activity.
This is the code that I am using to take the screenshot:
Function to take screen shot
public static void tmpScreenshot(Bitmap bmp, Context context){
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(context, CostActivity.class);
in1.putExtra("image", filename);
context.startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
}
Function to receive screenshot
private void loadTmpBitmap() {
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
ImageView imageView = findViewById(R.id.test);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 120, 120, false));
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Even though the Screenshot was taken, it was black when it is passed to another activity.
In addition, the Screenshot only appeared after I pressed the back button
Can anyone help me with the code to take a screenshot with ARCore? Or what am I doing wrong?
It is not possible to take a screenshot of a SurfaceView using your method. If you do then the screenshot will be black, as it only works for regular views.
What you need to use is pixelcopy.
private void takePhoto() {
ArSceneView view = arFragment.getArSceneView();
// Create a bitmap the size of the scene view.
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
// Create a handler thread to offload the processing of the image.
final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();
// Make the request to copy.
PixelCopy.request(view, bitmap, (copyResult) -> {
if (copyResult == PixelCopy.SUCCESS) {
try {
saveBitmapToDisk(bitmap);
} catch (IOException e) {
Toast toast = Toast.makeText(VisualizerActivity.this, e.toString(),
Toast.LENGTH_LONG);
toast.show();
return;
}
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Screenshot saved in /Pictures/Screenshots");
} else {
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Failed to take screenshot");
}
handlerThread.quitSafely();
}, new Handler(handlerThread.getLooper()));
}
public void saveBitmapToDisk(Bitmap bitmap) throws IOException {
// String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots/";
if (videoDirectory == null) {
videoDirectory =
new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Screenshots");
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
String formattedDate = df.format(c.getTime());
File mediaFile = new File(videoDirectory, "FieldVisualizer"+formattedDate+".jpeg");
FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}
visitingCardDialog.setContentView(R.layout.visitingcardtemplate1);
Button button = (Button) visitingCardDialog.findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RelativeLayout shareLayout = (RelativeLayout) visitingCardDialog.findViewById(R.id.vistingcard);
shareLayout.setDrawingCacheEnabled(true);
shareLayout.buildDrawingCache();
Bitmap bm = shareLayout.getDrawingCache();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, bytes);
loadImage(bm)
visitingCardDialog.dismiss();
}
});
visitingCardDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
visitingCardDialog.show();
this is my load function
it load Bitmap on photoeditorview
photoeditorview is object of Photoeditorview Class
private void loadImage(Bitmap image) {
phoroEditorView.getSource().setImageBitmap(image);
}
this worked for me!
RelativeLayout shareLayout = (RelativeLayout) visitingCardDialog.findViewById(R.id.vistingcard);
shareLayout.setDrawingCacheEnabled(true);
shareLayout.buildDrawingCache();
Bitmap bm = shareLayout.getDrawingCache();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, bytes);
try {
bm = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
//Snapshot.CroppedBitmap= Bitmap.createBitmap(shareLayout.getDrawingCache(true));
loadImage(decoded);
visitingCardDialog.dismiss();
Hey I have an app that choose an image from the gallery , resizing it and uploading it to ftp server , but I have notice that in some photo's the app flips the image horizontally and upload it backwards, I can't figure out why it is happening (It only happened on some photos and on others not, usually happened on photos taken from my camera)
Here is the code for the resize part:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK&&data!=null) {
selectedImageURI = data.getData();
showUri = data.getData();
imagePath = RealPathUtil.getPath(this,data.getData());
loadedImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
//loadedImage.setImageURI(data.getData());
Glide.with(this).load(data.getData())
.into((ImageView) findViewById(R.id.upload_image1));
ImageView m =(ImageView)findViewById(R.id.remove_image);
m.setFocusable(true);
m.setVisibility(View.VISIBLE);
File file = new File(RealPathUtil.getPath(this,data.getData()));
Bitmap bitmap = decodeFile(file);
ImageResizer(bitmap);
}
}
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_SIZE=200;
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
Bitmap bit1 = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
//Matrix matrix = new Matrix();
//matrix.postRotate(45);
// Bitmap rotatedBitmap = Bitmap.createBitmap(bit1 , 0, 0, bit1 .getWidth(), bit1 .getHeight(), matrix, true);
return bit1;
} catch (FileNotFoundException e) {}
return null;
}
private void ImageResizer(Bitmap bitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Pic");
if(!myDir.exists()) myDir.mkdirs();
String fname = "resized.png";
File file = new File (myDir, fname);
if (file.exists()){
file.delete();
Log.d("exist","replace");
SaveResized(file, bitmap);
} else {
SaveResized(file, bitmap);
Log.d("saved","now");
}
selectedImageURI = Uri.fromFile(file);
imagePath = RealPathUtil.getPath(this,selectedImageURI);
}
private void SaveResized(File file, Bitmap bitmap) {
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
can someone help me and tell me why is it happening?
I am trying to get an image from gallery or take one using camera in android. taking one using camera app works so fine but getting an image from gallery returs a nullpointer when compressing. below shows my code for sellecting from gallery and camera
#Override
protected void onActivityResult(int requestCode, int resultCode, #NonNull Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST1) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
image_String = SessionManager.encodeTobase64(thumbnail);
Log.d("bm", image_String.toString());
profile_pic.setImageBitmap(thumbnail);
} else if (requestCode == SELECT_FILE1) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(projection[0]);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
cursor.close();
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
image_String = SessionManager.encodeTobase64(bm);
Log.d("bm", image_String.toString());
profile_pic.setImageBitmap(bm);
}
}
}
and here is my mothhod to perform the encoding of the imgage i just got
public static String encodeTobase64(Bitmap img){
Bitmap image = img;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
return imageEncoded;
}
can't figure out the encode method signals an error when compresing the bitmap taken from gallery of device. Please help me out
My program generates several display keys, and I would like to assign each icon. The assets hold icon. But android does not load icons
button.setText(shop.getName());
Drawable icon;
int s = shop.getId();
String sk = Integer.toString(s);
String imageUri = "file:///android_asset/shop"+sk+".png";
Log.w("imageURI", imageUri);
Uri uri=Uri.parse(imageUri);
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
icon = Drawable.createFromStream(inputStream, uri.toString() );
} catch (FileNotFoundException e) {
icon = getResources().getDrawable(R.drawable.shopping1);
}
Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 100, 100, true));
button.setCompoundDrawablesWithIntrinsicBounds( null, d, null, null );
Log: ... file:///android_asset/shop1.png
Try this:
button.setText(shop.getName());
Drawable icon;
int s = shop.getId();
String sk = Integer.toString(s);
String imageUri = "file:///android_asset/shop"+sk+".png";
Log.w("imageURI", imageUri);
Uri uri=Uri.parse(imageUri);
InputStream is;
try {
is = this.getContentResolver().openInputStream( uri );
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 10;
Bitmap preview_bitmap=BitmapFactory.decodeStream(is,null,options);
Drawable icon = new BitmapDrawable(getResources(),preview_bitmap);
} catch (FileNotFoundException e) {
//set default image from the button
icon = getResources().getDrawable(R.drawable.shopping1);
}
button.setBackground(icon);