I want to export an image to csv, but my application crashes whenever trying to do this. In my application I have a question "which brands do you recognize ?", and wanted to let the user answer by selecting a checkbox along with the corresponding ImageView. The objective is to save both question(a string) and answer(an image) to csv or doc by clicking on a button, but the application crashes and only the string is printed in the generated csv.
public class Page3 extends Activity implements OnClickListener {
Intent myIntent;
TextView question4;
CheckBox one, two, three;
ImageView one1, two2, three3;
Bitmap bmp1, bmp2, bmp3;
String ques4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page3);
initialize();
}
private void initialize() {
Button prev = (Button) findViewById(R.id.page3previous);
Button next = (Button) findViewById(R.id.page3next);
next.setOnClickListener(this);
prev.setOnClickListener(this);
question4 = (TextView) findViewById(R.id.question4tv);
one1 = (ImageView) findViewById(R.id.imageView1);
two2 = (ImageView) findViewById(R.id.imageView2);
three3 = (ImageView) findViewById(R.id.imageView3);
one = (CheckBox) findViewById(R.id.checkBox1);
two = (CheckBox) findViewById(R.id.checkBox2);
three = (CheckBox) findViewById(R.id.checkBox3);
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.page3previous:
myIntent = new Intent(Page3.this, Page2.class);
startActivity(myIntent);
break;
case R.id.page3next:
ques4 = question4.getText().toString();
if (one.isChecked()) {
one1.buildDrawingCache();
bmp1 = one1.getDrawingCache();
setBitMapOneTwoThree(bmp1, bmp3, bmp2, ques4);
} else if (two.isChecked()) {
two2.buildDrawingCache();
bmp2 = two.getDrawingCache();
setBitMapOneTwoThree(bmp1, bmp3, bmp2, ques4);
} else if (three.isChecked()) {
three3.buildDrawingCache();
bmp3 = three3.getDrawingCache();
setBitMapOneTwoThree(bmp1, bmp3, bmp2, ques4);
} else if (two.isChecked() && one.isChecked()) {
one1.buildDrawingCache();
bmp1 = one1.getDrawingCache();
two2.buildDrawingCache();
bmp2 = two.getDrawingCache();
setBitMapOneTwoThree(bmp1, bmp3, bmp2, ques4);
} else if (two.isChecked() && three.isChecked()) {
two2.buildDrawingCache();
bmp2 = two.getDrawingCache();
three3.buildDrawingCache();
bmp3 = three3.getDrawingCache();
setBitMapOneTwoThree(bmp1, bmp3, bmp2, ques4);
} else if (one.isChecked() && three.isChecked()) {
three3.buildDrawingCache();
bmp3 = three3.getDrawingCache();
one1.buildDrawingCache();
bmp1 = one1.getDrawingCache();
setBitMapOneTwoThree(bmp1, bmp3, bmp2, ques4);
} else if (one.isChecked() && three.isChecked() && two.isChecked()) {
three3.buildDrawingCache();
bmp3 = three3.getDrawingCache();
two2.buildDrawingCache();
bmp2 = two.getDrawingCache();
one1.buildDrawingCache();
bmp1 = one1.getDrawingCache();
setBitMapOneTwoThree(bmp1, bmp3, bmp2, ques4);
}
myIntent = new Intent(Page3.this, Page4.class);
startActivity(myIntent);
break;
}
}
private void setBitMapOneTwoThree(Bitmap bmp12, Bitmap bmp32, Bitmap bmp22,
String ques42) {
bmp12 = this.bmp1;
bmp32 = this.bmp3;
bmp22 = this.bmp2;
ques42 = this.ques4;
generateCsvFile("Image.csv", bmp12, bmp32, bmp22, ques42);
}
private void generateCsvFile(String string, Bitmap bmp12, Bitmap bmp32,
Bitmap bmp22, String ques42) {
try {
File root = Environment.getExternalStorageDirectory();
File gpxfile = new File(root, string);
FileWriter writer = new FileWriter(gpxfile);
FileOutputStream fOut = new FileOutputStream(gpxfile);
writer.append(ques42);
writer.flush();
writer.close();
bmp12.compress(Bitmap.CompressFormat.PNG, 85, fOut);
bmp32.compress(Bitmap.CompressFormat.PNG, 85, fOut);
bmp22.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Since csv is a text format, you have to encode each bitmap into its own base64 string before you can insert them into a csv file.
Here is an online converter for a quick example of what I'm talking about.
Here is a code example for encoding an image into a base64 string. And once you need to deserialize the images from the csv file, here is the code for decoding a base64 string back into its original binary format.
Related
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.
In My Code The image is not open in ImageView from sdcard i already checked the permissions in 'manifest.xml'.
Same if i try to open it using static name then it will showed by ImageView but not dynamically.
Main Activity
private OnClickListener OnCapture = new OnClickListener() {
#Override
public void onClick(View v) {
String time = mCamUtils.clickPicture();
nextActivity = new Intent(MainActivity.this,EffectActivity.class);
nextActivity.putExtra("ImageName", time);
startActivity(nextActivity);
finish();
}
};
EffectActivity
public class EffectActivity extends Activity {
Intent getActivity = null;
ImageView image = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.effectactivity);
getActivity = getIntent();
String name = getActivity.getStringExtra("ImageName");
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
Toast.makeText(getApplicationContext(), path, Toast.LENGTH_LONG).show();
image = (ImageView) findViewById(R.id.imageView1);
File f = new File(path);
byte[] b = new byte[(int)f.length()];
if(f.exists())
{
try
{
if(f.exists())
{
FileInputStream ff = new FileInputStream(f);
ff.read(b);
Bitmap g = BitmapFactory.decodeFile(path);
image.setImageBitmap(g);
ff.close();
}
else
{
Toast.makeText(getApplicationContext(), "ELSE", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
}
}
}
}
I am trying to open image which i saved in before this activity and i catch the name of image here but that does not show the image.
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
In this line try changing "JPG" into "jpg".i think your file extension might be in lowercase letter and it might say f.exists false.
Hope it will help.
String fname = "Pic-" + System.currentTimeMillis() + ".png";
File image= new File(imagesFolder, fname);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
picturePath=image.getAbsolutePath();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bitmapOptions);
imageView.setImageBitmap(bitmap);
try this code
I save a picture from imageView to SD. The image is saved.
The problem is that there is the first image, and saving the next image again saved the first with a different name.
As I understand need to catch the moment when the picture from imageView is loaded into playImage. But how to do it?
Thank's.
Load the image in imageView and save to sd:
public class Gallery extends Activity implements OnClickListener {
String item;
Button btnsave, btnhome;
ImageView playImage;
String fotoname;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
btnhome = (Button) findViewById(R.id.btn_home);
btnhome.setOnClickListener(this);
btnsave = (Button)findViewById(R.id.btn_save);
btnsave.setOnClickListener(this);
playImage = (ImageView)findViewById(R.id.displayImage);
final ImageView playImage = (ImageView) findViewById(R.id.displayImage);
final LinearLayout myGallery = (LinearLayout) findViewById(R.id.mygallery1);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
item = extras.getString("item");
if(item.equals("Item")){
try {
String galleryDirectoryName = "ITEM/item";
String[] listImages = getAssets().list(galleryDirectoryName);
for (String imageName : listImages) {
InputStream is = getAssets().open(galleryDirectoryName + "/" + imageName);
final Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(350, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bitmap);
imageView.setPadding(10, 70, 10, 70);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playImage.setImageBitmap(bitmap);
playImage.setPadding(5, 0, 5, 0);
}
});
myGallery.addView(imageView);
}
} catch (IOException e) {
Log.e("GalleryWithHorizontalScrollView", e.getMessage(), e);
}
}
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btn_save:
playImage.setDrawingCacheEnabled(true);
Bitmap bitmap = playImage.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/." + (getString(R.string.app_name)));
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Toast.makeText(this, (getString(R.string.saved)), Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
}
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(newDir, fotoname);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
break;
case R.id.btn_home:
finish();
}
}
}
Check this.
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ll.setDrawingCacheEnabled(true);
Bitmap bitmap = ll.getDrawingCache();
// bitmap = Bitmap.createBitmap(480, 800,
// Bitmap.Config.ARGB_8888);
String root = Environment.getExternalStorageDirectory()
.toString();
File newDir = new File(root + "/Collage_Maker");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "cm_"+n + ".jpg";
File file = new File(newDir, fotoname);
String s = file.getAbsolutePath();
Log.i("Path of saved image.", s);
System.err.print("Path of saved image." + s);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
Toast.makeText(getApplicationContext(), "Photo Saved "+ fotoname,
Toast.LENGTH_SHORT).show();
out.close();
} catch (Exception e) {
Log.e("Exception", e.toString());
}
}
});
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();
}
Hey i am new in android application development.i currently develop
application, in some phase of that application deal with the image
store , retrieve and delete
how can i store whole image in android ? and how can i retrieve more
than one images which i uploaded in SQLite wants in gallery view?
please give me some guidance or link of blogs which deal with such
image processing in android
If u are dealing with images copy the image to separate folder and store the path in database OR store the image bytearray in db if size of image is small.
try this
public class ImageConvertScreen extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button img_byte,byte_img;
ImageView image;
TextView value;
public ByteArrayOutputStream bos;
public Bitmap bm;
public byte[] bitmapdata;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nextr);
image = (ImageView) findViewById(R.id.img_convert);
value=(TextView)findViewById(R.id.convert_txt);
img_byte =(Button)findViewById(R.id.img_byte);
byte_img =(Button)findViewById(R.id.byte_img);
img_byte.setOnClickListener(this);
byte_img.setOnClickListener(this);
String imgName = "ic_launcher";
String KEY_IMG = "/mnt/sdcard/DCIM/Camera/IMG_20121021_150153.jpg";
File f = new File(Environment.getExternalStorageDirectory(), KEY_IMG);
String path =Environment.getExternalStorageDirectory().getPath()+"/image4.png";
//bm = BitmapFactory.decodeFile(path);
bm = BitmapFactory.decodeResource(getResources(),getResId(imgName, R.drawable.class));
bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 20 , bos);
}
public void onClick(View v) {
if (v == img_byte) {
bitmapdata = bos.toByteArray();
Log.w("Image Conversion", String.valueOf(bitmapdata.length));
String converted_txt="";
Toast.makeText(getBaseContext(), ""+bitmapdata.length,1).show();
for (int i = 0; i < bitmapdata.length; i++) {
Log.w("Image Conversion", String.valueOf(bitmapdata[i]));
converted_txt=converted_txt+bitmapdata[i];
}
saveImageOnSDCard1("testingImg",bitmapdata);
value.setText(converted_txt);
value.setVisibility(View.VISIBLE);
image.setVisibility(View.INVISIBLE);
} else if (v==byte_img){
bm = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
image.setImageBitmap(bm);
image.setVisibility(View.VISIBLE);
value.setText("");
value.setVisibility(View.INVISIBLE);
Log.w("Image Conversion", "converted");
}
}
public int getResId(String variableName, Class<?> c) {
Field field = null;
int resId = 0;
try {
field = c.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
public static void saveImageOnSDCard1(String imageName, byte[] data) {
File file1 = new File(Environment.getExternalStorageDirectory()
+ "/isus/");
if (!file1.exists()) {
boolean isCreated = file1.mkdirs();
Log.e("Directory Created", "Directory Created " + isCreated);
}
File file = new File(Environment.getExternalStorageDirectory()
+ "/isus/" + imageName + ".png");
Log.i("path",""+file.getAbsolutePath().toString());
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data);
} catch (Exception e) {
Log.i("err",""+e.getLocalizedMessage());
} finally {
try {
fileOutputStream.close();
} catch (Exception e2) {
}
}
}
}