The main theme of my app is, user has to select images from his device gallery, and those selected images are turned into a GIF. I'm converting those selected images into bitmap and I am using this GIFEncoder.java file to converted selected images into a GIF, and I have achieved it. when I check it in my folder, GIF was created but when I open the GIF is was not animating just a black screen was appeared.
Here is my MainActivity looks like:
public class MainActivity extends AppCompatActivity {
private static final int SELECT_PHOTO = 102;
private FileOutputStream outStream;
ArrayList<Bitmap> bitmaps = new ArrayList<>();
private Button generateImageGIF, selectImages;
String BASE_PATH = Environment.getExternalStorageDirectory().toString() + File.separator + "ImagesToGif";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File mydir = new File(BASE_PATH);
if (!mydir.exists()) {
mydir.mkdirs();
}
generateImageGIF = (Button) findViewById(R.id.generate_image_gif);
selectImages = (Button) findViewById(R.id.select_images);
selectImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
generateImageGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Toast.makeText(getApplicationContext(), "gif creation started", Toast.LENGTH_LONG).show();
outStream = new FileOutputStream(BASE_PATH + File.separator + getString(R.string.app_name) + ".gif");
outStream.write(generateGIF());
outStream.close();
Toast.makeText(getApplicationContext(), "gif creation ended", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
Bitmap bitmap1 = BitmapFactory.decodeFile(String.valueOf(data.getData()));
bitmaps.add(bitmap1);
}
}
public byte[] generateGIF() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}
Related
I want to display the image I took inside an imageview but it doesn't display the image. I checked these pages but got no results:
Image captured from camera not displaying in imageview android
Capture Image from Camera and Display in Activity
my activity:
public class MainActivity extends AppCompatActivity {
Button btncam;
ImageView imgpic;
final int take=10;
long name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgpic=(ImageView)findViewById(R.id.imgpic);
btncam=(Button)findViewById(R.id.btncamera);
btncam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
name=System.currentTimeMillis();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(G.appadress+"/"+name+".jpg")));
startActivityForResult(intent,take);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch (requestCode){
case take:
Bitmap bitmap= BitmapFactory.decodeFile(G.appadress+"/"+name+".jpg");
imgpic.setImageBitmap(bitmap);
}
}
}
class G:
public class G extends Application {
public static Context context;
public static String appadress= Environment.getExternalStorageDirectory().getAbsolutePath();
#Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
File file=new File(appadress);
file.mkdirs();
}
}
manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try:
public class MainActivity extends AppCompatActivity {
Button btncam;
ImageView imgpic;
final int take = 10;
Bitmap bitmap;
long name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgpic = (ImageView) findViewById(R.id.imgpic);
btncam = (Button) findViewById(R.id.btncamera);
btncam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
super.onActivityResult(requestCode, resultCode, data);
if (data.getExtras() != null) {
bitmap = (Bitmap) data.getExtras().get("data");
try {
File imageFile = createImageFile();
OutputStream stream = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
imgpic.setImageBitmap(bitmap);
}
}
}
public File createImageFile() throws IOException {
// Create an imageView file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getStorageDir();
File image = File.createTempFile(
imageFileName, /* prefix */
".jpeg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
return image;
}
private File getStorageDir() {
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/PathPhoto"); //Environment.DIRECTORY_PICTURES -->> it is path for Pictures
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
return storageDir;
}
}
I prefer Android Image Cropper library, automatically handles Importing or Capturing images.
private void onCaptureClick(){
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
class G:
public class G extends Application {
public static Context context;
public static String appadress= Environment.getExternalStorageDirectory().getAbsolutePath()+"/reza";
#Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
File file=new File(appadress);
file.mkdirs();
}
}
this is my code it store captured picture form camera and save it on the SDcard but Now i want to enhance this code to taking pictures every 5 seconds If any body having an idea how to do this ,please share
public class MainActivity extends ActionBarActivity {
private final int requestCode = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int pictureCounter = 10;
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should implement a runnable interface that uses threads. This way you could call the function on the OnClick method, then call Thread.sleep(timeinmilliseconds), then call the function inside the onClick method again, as many times as needed.
Here is an example of how to use threads:
http://www.wideskills.com/java-tutorial/java-threads-tutorial
In my app, i can take a picture and save in gallery(folder 'camera').But i need save it in a specific folder in external memory.This is my code.How i can do it?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_pic);
init();
getPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle ex = data.getExtras();
bitmap = (Bitmap) ex.get("data");
myPic.setImageBitmap(bitmap);
}
}
This should do it:
private void createDirectoryAndSaveFile(Bitmap imgSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File imageDirectory = new File("/sdcard/DirName/");
imageDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imgSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Threr is what i have done. On my activity. I take 2 picture correctly but if i change the orientation of the phone app crash
public class MyactivityTakePicture extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//initialisation
setContentView(R.layout.picture_main_layout);
img1 = (ImageView)findViewById(R.id.photo1);
img2 = (ImageView)findViewById(R.id.photo2);
//creation des dossiers
dir1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/g0/";
newdir1 = new File(dir1);
newdir1.mkdirs();
dir2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/g1/";
newdir2 = new File(dir2);
newdir2.mkdirs();
capture1 = (Button) findViewById(R.id.btnCapture1);
capture1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
takepicture1();
}
});
capture2 = (Button) findViewById(R.id.btnCapture2);
capture2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
takepicture2();
}
});
if(savedInstanceState != null){
filePath1 = savedInstanceState.getString("chemin1");
filePath2 = savedInstanceState.getString("chemin2");
bitmap1 = BitmapFactory.decodeFile(filePath1);
img1.setImageBitmap(bitmap1);
//filePath2 = savedInstanceState.getString("chemin1");
Log.w("A", ""+filePath1);
Log.i("F", ""+filePath2);
bitmap2 = BitmapFactory.decodeFile(filePath2);
img2.setImageBitmap(bitmap2);
}
}
//prise de photo N°1
..................
//prise de photo N°2
protected void takepicture2(){
//nom des photos photo1.jpg, photo2.jpg ...
count++;
file2 = dir2+"photo.jpg";
File newfile2 = new File(file2);
filePath2 = dir2+"photo.jpg";
try {
newfile2.createNewFile();
} catch (IOException e) {
Log.e("Error", e.toString());
}
Uri outputFileUri2 = Uri.fromFile(newfile2);
Intent cameraIntent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent2.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri2);
startActivityForResult(cameraIntent2, TAKE_PHOTO_CODE2);
}
//Enregistrement OK
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE1 && resultCode == RESULT_OK) {
Log.d("CameraDemo1", "Pic saved");
bitmap1 = BitmapFactory.decodeFile(filePath1);
img1.setImageBitmap(bitmap1);
}
if (requestCode == TAKE_PHOTO_CODE2 && resultCode == RESULT_OK){
Log.d("CameraDemo2", "Pic saved");
bitmap2 = BitmapFactory.decodeFile(filePath2);
img2.setImageBitmap(bitmap2);
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(newdir1==null){
newdir1 = new File(file1);
}// if
if(newdir2==null){
newdir2 = new File(file2);
}
outState.putString("chemin1", filePath1);
outState.putString("chemin2", filePath2);
}
}
First, Activity lauch correctely, take the two picture.
If i try to change orientation of my phone. She crash.
Please you see?
The problem is that your images aren't getting deallocated from memory.
java.lang.OutOfMemoryError: bitmap size exceeds VM budget
read this articles, would be helpful for you
http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html
http://androidactivity.wordpress.com/2011/09/24/solution-for-outofmemoryerror-bitmap-size-exceeds-vm-budget/
http://mobi-solutions.blogspot.mx/2010/08/how-to-if-you-want-to-create-and.html
UPDATE:
I have seen your code and i suggest the use of the method onDestroy() to set the bitmap instances to null:
#Override
protected void onDestroy(){
super.onDestroy();
bitmap1 = null;
bitmap2 = null;
}
My app takes a picture using the phones camera and stores the picture in the phones gallery. I would like to then get that picture path and store it in my datastore. Can someone please help me? Heres my code:
public void onClick(View v){
switch(v.getId())
{
case R.id.btnLoadPic:
//Options for the dialogue menu
final CharSequence[] items = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose an Option");
builder.setItems(items, new DialogInterface.OnClickListener() {
/**
* Make onclick functionality for the options in the dialogue menu
*/
public void onClick(DialogInterface dialog, int item) {
// Camera option
if (item == 0){
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)){
//Toast.makeText(this, "camera", Toast.LENGTH_SHORT).show();
dispatchTakePictureIntent(11);
} else {
Toast.makeText(null, "No camera avalible", Toast.LENGTH_SHORT).show();
}
}
// Gallery option this works fine
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
//handleSmallCameraPhoto(takePictureIntent);
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
ImageView mImageView = (ImageView) this.findViewById(R.id.imagePlayer);
mImageView.setImageBitmap(mImageBitmap);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
handleSmallCameraPhoto(data);
}
The last bits of codes accesses the camera and displays the picture in the imageview. How do i get that picture path in a string format?
This will help. Tested and worked!
public class MainActivity extends Activity {
private static final int REQUEST_IMAGE = 100;
private static final String TAG = "MainActivity";
TextView tvPath;
ImageView picture;
File destination;
String imagePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvPath = (TextView) findViewById(R.id.idTvPath);
picture = (ImageView) findViewById(R.id.idIvImage);
String name = dateToString(new Date(),"yyyy-MM-dd-hh-mm-ss");
destination = new File(Environment.getExternalStorageDirectory(), name + ".jpg");
Button click = (Button) findViewById(R.id.idBtnTakePicture);
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();
tvPath.setText(imagePath);
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
picture.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
tvPath.setText("Request cancelled");
}
}
public String dateToString(Date date, String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(date);
}
}
Dont forget to add these in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>