Imageview display black image after decode in android - android

I'm working with Image steganography in android right now. For that I need to convert the image into bits array and decode it back. But when I try to convert my image back into its original shape, it showing only a black colour in my ImageView. Here is my code
btnEncode = (Button) findViewById(R.id.encode);
btnEncode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//imgPath.setText(imageToBase64(selectedImagePath));
ImageView imageView=(ImageView)findViewById(R.id.imageView1);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
bytes = getBytesFromBitmap(bitmap);
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
//To save the binary in newString
String ImageEncoded=new String(binary.toString());
TextView imgData=(TextView)findViewById(R.id.txtResult);
imgData.setText(ImageEncoded);
}
});
btnDecode = (Button) findViewById(R.id.decode);
btnDecode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
ImageView imageView=(ImageView)findViewById(R.id.imageView1);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
bytes = getBytesFromBitmap(bitmap);
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ImageView image = (ImageView) findViewById(R.id.imageView2);
image.setImageBitmap(bmp);
}
});
public static byte[] getBytesFromBitmap(Bitmap bitmap)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}

Its about your converter format. Use CompressFormat.PNG instead of CompressFormat.JPEG. This caused by "JPEGs don't do transparency like PNG".

Related

How to save an image attached to the image view?

I am using a Glide library for loading remote URLs into ImageView's.
I want to save the image from this ImageView to gallery. (I don't want to make another network call again to download the same image).
How we can achieve this?
Glide.with(yourApplicationContext))
.load(youUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
//set bitmap to imageview and save
}
};
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, false);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 60, byteArrayOutputStream);
String fileName = "image.jpeg";
File file = new File("your_directory_path/"
+ fileName);
try {
file.createNewFile();
// write the bytes in file
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(byteArrayOutputStream.toByteArray());
// remember close the FileOutput stream
fileOutputStream.close();
ToastHelper.show(getString(R.string.qr_code_save));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ToastHelper.show("Error");
}
Note : If your drawble is not always an instanceof BitmapDrawable
Bitmap bitmap;
if (mImageView.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
} else {
Drawable d = mImageView.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Try this
I haven't try this way. But i think this match your problem. Put this code on onBindViewHolder of your RecyclerView adapter.
Glide.with(yourApplicationContext))
.load(youUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
//Set bitmap to your ImageView
imageView.setImageBitmap(bitmap);
viewHolder.saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Save bitmap to gallery
saveToGallery(bitmap);
}
});
}
};
This might help you
public void saveBitmap(ImageView imageView) {
Bitmap bitmap = ((GlideBitmapDrawable) imageView.getDrawable()).getBitmap();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/My Images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception ex) {
//ignore
}
}

How to save the image?

I am using Picasso to fetch image and I just want to save the image.Below code is not working for me to save the image.
public class DownloadImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mindmaps);
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
Picasso.with(this)
.load("http://i.imgur.com/DvpvklR.png")
.into(imageView);
final Button btntakephoto = (Button) findViewById(R.id.save);
btntakephoto.setOnClickListener((View.OnClickListener) this);
}
public void onClick(View v){
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Drawable image = imageView.getDrawable();
if (image != null && image instanceof BitmapDrawable) {
BitmapDrawable drawable = (BitmapDrawable) image;
Bitmap bitmap = drawable.getBitmap();
try {
File file = new File("path where you want to save");
FileOutputStream stream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
On pressing the save button image should be saved in the gallery.
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
try this,
call this method from button click:
private void saveImage() {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Drawable image = imageView.getDrawable();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), image);
OutputStream out = null;
String fileName = "MyImage.jpg";
String mPath = "";
try {
out = mActivity.openFileOutput(fileName, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
File f = mActivity.getFileStreamPath(fileName);
mPath = f.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
Logger.logger("URI :" + mPath);
}
Make your DownloadImage class implement View.OnClickListener interface.

Download/save viewing picture from application resource

How do I set my application to download/save to phone the image I am previewing?
I Tried with the code below but it's not working, it gives me error and I can't figure out where is that error. So what am I supposed to replace and with what?
public class FullImageActivity extends Activity {
Bitmap bm;
boolean isSDAvail=false, isSDWriteable = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.full_image);
//AdView ad = (AdView) findViewById(R.id.adView);
//ad.loadAd(new AdRequest());
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ImageAdapter imageAdapter = new ImageAdapter(this);
final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
checkSDstuff();
}
private void checkSDstuff() {
// TODO Auto-generated method stub
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
//write
isSDAvail = true;
isSDWriteable =true;
}else if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
//read only
isSDAvail =true;
isSDWriteable = false;
}else{
//uh oh
isSDAvail = false;
isSDWriteable =false;
}
Button buttonSave = (Button)findViewById(R.id.download);
buttonSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isSDAvail && isSDWriteable){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String name = filename.getText().toString(); //how to set name from postion
File file = new File(path, name + ".jpeg");
path.mkdirs();
InputStream is = getResources().openRawResource(R.drawable.pic); //here to set (imageAdapter.mThumbIds[position]) from position of ImageView
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
}
}
});
}
Here is code to create a bitmap from an ImageView:
public Bitmap getBitmapFromImageView(ImageView imageView) {
int viewWidth = imageView.getWidth();
int viewHeight = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
imageView.layout(0, 0, viewWidth, viewHeight);
imageView.draw(canvas);
return bitmap;
}
Then to save the Bitmap:
try {
Bitmap bmp = getBitmapFromImageView(imageView);
FileOutputStream out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}

Processing bytearray shows no difference

I wanted to write a simple processing function.
It should run like this:
Load a Jpeg
Convert it to Bitmap
save bitmap as byte array
process
data convert back to bitmap show Image.
public class MainActivity extends Activity {
ImageView imgView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView1);
AssetFileDescriptor asf;
String filename = Environment.getExternalStorageDirectory() + "/Test/"
+ "DSC00751.JPG";
Bitmap map = BitmapFactory.decodeFile(filename);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
// Convert image so it can be stored in byteArray
map.compress(CompressFormat.JPEG, 100, bout);
byte[] array = bout.toByteArray();
// Process image.
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
array[i] = (byte) 200;
}
}
// Convert result and display
Bitmap bmp = BitmapFactory.decodeByteArray(array, 0, array.length);
imgView.setImageBitmap(bmp);
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
}
I get a whitescreen in return. No matter how my processing code looks like.
I tried using foreach(byte b : array) before, but this always returned the original image.
What am I doing wrong?
// Process image.
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
array[i] = (byte) 200;
}
}
in this code you are changing image bytes!! so thats why it appears white!!
what else?
anyway, if you need to process an image you need to do it like that :
Bitmap bitmap =...;
int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
now you have the pixels array of the image (int[])

Why Bitmap to Base64 String showing black background on webview in android?

I am using a code that combine to images into 1 by using canvas . I show that image to ImageView it looks fine. But when I try to show that into WebView it show background black to right that image. I try to change the background color in HTML but it not change color. or make transparent. Can anyone help? Result is here The above image is in ImageView and below is in WebView.
public class MyBimapTest extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img1 = (ImageView) findViewById(R.id.ImageView01);
img1.setVisibility(View.INVISIBLE);
Drawable dra1 = img1.getDrawable();
Bitmap map1 = ((BitmapDrawable) dra1).getBitmap();
ImageView img2 = (ImageView) findViewById(R.id.ImageView02);
img2.setVisibility(View.INVISIBLE);
Drawable dra2 = img2.getDrawable();
Bitmap map2 = ((BitmapDrawable) dra2).getBitmap();
// ***
ByteArrayOutputStream baos = new ByteArrayOutputStream();
map1.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String abc = Base64.encodeBytes(b);
byte[] byt = null;
try {
byt = Base64.decode(abc);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map1 = BitmapFactory.decodeByteArray(byt, 0, byt.length);
// ***
Bitmap map = combineImages(map1, map2);
ByteArrayOutputStream bbb = new ByteArrayOutputStream();
map.compress(Bitmap.CompressFormat.JPEG, 100, bbb);
byte[] bit = bbb.toByteArray();
String imgToString = Base64.encodeBytes(bit);
String imgTag = "<img src='data:image/jpg;base64," + imgToString
+ "' align='left' bgcolor='ff0000'/>";
WebView webView = (WebView) findViewById(R.id.storyView);
webView.loadData(imgTag, "text/html", "utf-8");
Drawable end = new BitmapDrawable(map);
ImageView img3 = (ImageView) findViewById(R.id.ImageView03);
img3.setImageBitmap(map);
}
public Bitmap combineImages(Bitmap c, Bitmap s) {
Bitmap cs = null;
int width, height = 0;
width = c.getWidth() + (s.getWidth() / 2);
height = c.getHeight() + (s.getHeight() / 2);
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, c.getWidth() - (s.getWidth() / 2), c
.getHeight()
- (s.getHeight() / 2), null);
return cs;
}
}
The JPEG format does not support alpha transparency, which is why the transparent background becomes black when you convert your original image to JPEG.
Use the PNG format instead:
map1.compress(Bitmap.CompressFormat.PNG, 100, baos);
and
String imgTag = "<img src='data:image/png;base64," + imgToString
+ "' align='left' bgcolor='ff0000'/>";

Categories

Resources