天道酬勤,学无止境

cocos2dx save image in to gallery android

I want to take screenshots and save it in the gallery. What I have tried:

CCSize size = CCDirector::sharedDirector()->getWinSize();

CCRenderTexture* texture = CCRenderTexture::create((int)size.width, (int)size.height, kCCTexture2DPixelFormat_RGBA8888);
texture->setPosition(ccp(size.width/2, size.height/2));
texture->begin();
CCDirector::sharedDirector()->getRunningScene()->visit();
texture->end();
texture->saveToFile("scrshot.png", kCCImageFormatJPEG);

in iOS it is working perfectly and am able to save image in to documents, but the problem is in android :

There are two possibilities

1) texture->saveToFile("scrshot.png", kCCImageFormatJPEG); or texture->saveToFile("My path"); -> It compiles but where is the image saved?

2) Use JNI to save Bitmap file -> problem is how to cast CCRenderTexture to Bitmap and parse it.

评论

I solve this issue quickly but forgot to give the answer but now giving because it may help someone

My code is only for iOS and android

code is

CCSize size = CCDirector::sharedDirector()->getWinSize();

CCRenderTexture* texture = CCRenderTexture::create((int)size.width, (int)size.height, kCCTexture2DPixelFormat_RGBA8888);
texture->setPosition(ccp(size.width/2, size.height/2));
texture->begin();
CCDirector::sharedDirector()->getRunningScene()->visit();
texture->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

    std::string str =  CCFileUtils::sharedFileUtils()->getWritablePath();
    str.append("/imageNameToSave.png");
    const char * c = str.c_str();
    texture->saveToFile(c);
    SaveImageAndroidJNI(true);

#else

        texture->saveToFile("imageNameToSave.png", kCCImageFormatPNG);
        BridgeClass::shared()->saveTOAlbum();

#endif

In My BridgeClass

void BridgeClass:: saveTOAlbum(){

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *yourArtPath = [documentsDirectory stringByAppendingPathComponent:@"/imageNameToSave.png"];

    UIImage *image = [UIImage imageWithContentsOfFile:yourArtPath];

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"Photo Saved To Photos." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

For iOS it will save to gallery

For android there is a class androidJNI.cpp

void SaveImageAndroidJNI(bool visible){
        JniMethodInfo t;
        if (JniHelper::getStaticMethodInfo(t, "yourPackageName/ClassName"
                                           ,"SaveImageAndroidJNI"
                                           ,"(Z)V"))
        {
            t.env->CallStaticVoidMethod(t.classID,t.methodID,visible);
        }
    }

And android native method for save image to data/data

static void SaveImageAndroidJNI(final boolean visible)
{

    ContextWrapper c = new ContextWrapper(me);
    String path = c.getFilesDir().getPath() + "/imageNameToSave.png";
    System.out.println("Paht to check --"+path);
    File imgFile = new  File(path);

    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    ArrayList<Uri> uris = new ArrayList<Uri>();
    uris.add(Uri.parse(path));

    OutputStream output;
 // Find the SD Card path
    File filepath = Environment.getExternalStorageDirectory();

    // Create a new folder in SD Card
    File dir = new File(filepath.getAbsolutePath()
            + "/Your Folder Name/");
    dir.mkdirs();

    // Create a name for the saved image
    File file = new File(dir, "imageNameToSave.png");

    try {

        output = new FileOutputStream(file);

        // Compress into png format image from 0% - 100%
        myBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        output.flush();
        output.close();
    }

    catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    Intent intent = new Intent();
    Uri pngUri = Uri.fromFile(file);


    intent.setAction(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_STREAM, pngUri);
    intent.setType("image/jpeg");

        me.startActivity(Intent.createChooser(intent, "Share Image"));    
}

when access this image from data/data will not accessible directly here save this image to sd card and the access it from cocos2dx

but for android have to get writable path using getWritablePath function and parse this value to saveToFile function and the SaveImageAdmobJNI(true); will call native method ,in native method you can save take the image path and save it to gallery

Note: getWritablePath() - this function will give you the path from data->data->YOUR_PAKAGE

Feel free to ask queries.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Cocos2dx Android 启动后我坏掉的现象是onResume Activity 的图像精灵(Cocos2dx Android I'm broken phenomenon after the launch is an image sprite onResume Activity)
    问题 CCTexture2D *t = new CCTexture2D(); t->initWithData(imageData, kCCTexture2DPixelFormat_RGBA8888, sprite->getTexture()->getPixelsWide(), sprite->getTexture()->getPixelsHigh(), sprite->getTexture()->getContentSize()); CCSprite *ret = CCSprite::createWithTexture(t); 这样,只创建了标题和类似精灵的现象。 CCSprite *ret 对海滩上的水的效果精灵自定义图像。 IOS,Android,没有任何问题,onPause()->onResume(a)通过Ret图像变黑 如何解决? 回答1 任何未从文件加载的精灵在恢复后都会变黑,无论是用数据初始化的 CCTexture2D 还是 CCRenderTexture。 最简单的解决方案:停止使用动态纹理,从文件加载所有纹理。 解决方法:恢复放置在 cocos2d::CCApplication 子类中的事件回调 - 它是 applicationWillEnterForeground() 方法。 您可以在此方法中手动重新加载所有纹理。 例如,创建自己的接口 A
  • 在 Windows 7 上设置 Cococ2dx-3.5 环境时找不到 awk 文件(Awk file not found when Setting Up Cococ2dx-3.5 environment on Windows 7)
    问题 我正在尝试在 Windows 7 上设置 cocos2dx-3.5 环境。 以下是我对环境变量的值 NDK_ROOT = D:\Android\Cocos2dx\android-ndk-r10d-windows-x86\android-ndk-r10d SDK_ROOT = D:\Android\android-sdk 我没有设置ANDROID_NDK_ROOT环境变量,因为我遵循的教程没有设置它。 [但是,如果我将其设置为与 NDK_ROOT 相同的值,则会出现ANDROID_NDK_ROOT变量未指向目录的错误] 我正在测试 cpp-empty-test 项目 [android] 现在的问题是,当我通过 cygwin 终端给出命令“./ndkgdb.sh”时,它给了我找不到 awk 文件的错误。 据我了解它是在错误的路径上找到它。 它试图从 Project 文件夹中查找 awk 文件,而 awk 文件则放在 ndk 文件夹中。 我哪里做错了? 非常感谢您的预期帮助。 谢谢 编辑: 我的测试项目放在如下路径 D:\Android\Cocos2dx\cocos2d-x-3.5\cocos2d-x-3.5\tests\cpp-empty-test awk 文件可以在这里找到 D:\Android\Cocos2dx\android-ndk-r10d-windows-x86
  • Cocos2dx Android I'm broken phenomenon after the launch is an image sprite onResume Activity
    CCTexture2D *t = new CCTexture2D(); t->initWithData(imageData, kCCTexture2DPixelFormat_RGBA8888, sprite->getTexture()->getPixelsWide(), sprite->getTexture()->getPixelsHigh(), sprite->getTexture()->getContentSize()); CCSprite *ret = CCSprite::createWithTexture(t); In this way, only the title and sprite-like phenomenon is created. CCSprite *ret the effect of the water on the Beach the Sprite to customize the image. IOS, Android, without any problems, the onPause ()-> onResume (a) through Ret image turns black How to solve it?
  • 如何在Android Gallery中保存图像(How to save image in android gallery)
    问题 我尝试将图像保存到WathsappIMG中,但是当我转到Android图像画廊时,我看不到图像,并且可以从ES File Explorer中看到该图像到目录中 OutputStream output; // Find the SD Card path File filepath = Environment.getExternalStorageDirectory(); // Create a new folder in SD Card File dir = new File(filepath.getAbsolutePath() + "/WhatSappIMG/"); dir.mkdirs(); // Retrieve the image from the res folder BitmapDrawable drawable = (BitmapDrawable) principal.getDrawable(); Bitmap bitmap1 = drawable.getBitmap(); // Create a name for the saved image File file = new File(dir, "Wallpaper.jpg" ); try { output = new FileOutputStream(file); // Compress into png
  • android-将图像保存到图库(android - save image into gallery)
    问题 我有一个带有图片库的应用,我希望用户可以将其保存到自己的库中。 我创建了一个带有单个语音“保存”的选项菜单,但允许的问题是...如何将图像保存到图库中? 这是我的代码: @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menuFinale: imgView.setDrawingCacheEnabled(true); Bitmap bitmap = imgView.getDrawingCache(); File root = Environment.getExternalStorageDirectory(); File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg"); try { file.createNewFile(); FileOutputStream ostream = new FileOutputStream(file); bitmap.compress(CompressFormat.JPEG, 100, ostream); ostream.close(); } catch
  • 如何将我的imageView图像保存到Gallery中(Android开发)(How do I save my imageView image into Gallery (Android Development))
    问题 我试图创建一个onClick事件,以通过单击一个按钮将imageview保存到手机图库中,这是我的代码。 它不会保存到图库中,有人可以帮助我找出原因吗? sharebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View b) { // TODO Auto-generated method stub //attempt to save the image b = findViewById(R.id.imageView); b.setDrawingCacheEnabled(true); Bitmap bitmap = b.getDrawingCache(); //File file = new File("/DCIM/Camera/image.jpg"); File root = Environment.getExternalStorageDirectory(); File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg"); try { cachePath.createNewFile(); FileOutputStream ostream = new
  • 将图像保存在画廊 android 中(save image in gallery android)
    问题 我正在使用此代码来保存图像: URL url = null; try { url = new URL("image"); } catch (MalformedURLException e1) { e1.printStackTrace(); } Bitmap bmp = null; try { bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException e1) { e1.printStackTrace(); } OutputStream output; File filepath = Environment.getExternalStorageDirectory(); File dir = new File(filepath.getAbsolutePath() + "/folder name/"); dir.mkdirs(); File file = new File(dir, image + ".png"); Toast.makeText(HomeActivity.this, "Image Saved to SD Card", Toast.LENGTH_SHORT).show(); try { output = new
  • save image in gallery android
    I am using this code to save the image: URL url = null; try { url = new URL("image"); } catch (MalformedURLException e1) { e1.printStackTrace(); } Bitmap bmp = null; try { bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException e1) { e1.printStackTrace(); } OutputStream output; File filepath = Environment.getExternalStorageDirectory(); File dir = new File(filepath.getAbsolutePath() + "/folder name/"); dir.mkdirs(); File file = new File(dir, image + ".png"); Toast.makeText(HomeActivity.this, "Image Saved to SD Card", Toast.LENGTH_SHORT).show(); try { output
  • 如何从android画廊隐藏图像(how to hide images from android gallery)
    问题 我当前项目的一部分是从URL下载图像,然后保存到SDCard。 但是问题是sdcard中所有保存的图像都显示在android gallery页面中。 我想要的是“我不希望所有已保存的图像都在android画廊中。 ” 回答1 添加“ .nomedia”文件。 不工作? 尝试第二个选项。 将文件保存到以“。”开头的文件夹,例如/sdcard/.myimages/ 回答2 您可以使用以下代码创建.nomedia文件: String NOMEDIA=".nomedia"; File Folder = new File(Environment.getExternalStorageDirectory() + "/mydir"); if(Folder.mkdir()) { nomediaFile = new File(Environment.getExternalStorageDirectory() + "/mydir/"+ NOMEDIA); if(!nomediaFile.exists()){ nomediaFile.createNewFile(); } } 回答3 我找到了一种简单的方法(我认为是这样)。 在“ Android”文件夹(其中存在data和obb文件夹)中创建一个文件夹,然后将媒体(图片,视频等)放入您创建的文件夹中。 Gallery应用程序会忽略该“ Android
  • 在 Android 4.3 中将位图保存到磁盘/图库(Saving a bitmap to disk/gallery in Android 4.3)
    问题 我一直在使用系统保存截图的方式将我的位图保存到磁盘和图库中。 这适用于 Android 4.2 及之前版本,但不适用于 Android 4.3。 相关代码: Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); OutputStream out = resolver.openOutputStream(uri); 完整代码在这里。 然而,在 4.3(新的 Nexus 7)中,我在第二行得到一个 FileNotFoundException。 我在网站上看不到 4.3 中与此相关的任何更改。 那么将图像保存到磁盘和图库的正确方法是什么? 验证: 存储是用这种方法挂载的 imageUri 不为空(通常类似于“content://media/external/images/media/2034”) 清单具有权限 android.permission.WRITE_EXTERNAL_STORAGE 回答1 这是我将bitmaps保存到Gallery 的方式: Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri; //instantiate Uri
  • 将图像保存到android中的画廊(save the image to the gallery in android)
    问题 如何将相机拍摄的图像保存到图库中? 我有这个代码但不保存图像 private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents mCurrentPhotoPath = image.getAbsolutePath(); return image; } 几乎用这个 private void galleryAddPic() { Intent
  • Android-为什么我保存的图像没有出现在手机的默认图片库中?(Android - Why my saved image is not appearing in the default gallery of my phone?)
    问题 我正在尝试将应用程序中的图像保存到手机的默认图片库中。 如果我的手机上装有SD卡,则下面的代码可以完美地工作。 所保存的图像将出现在手机的图库中,并且与预期的一样: private Uri saveMediaEntry(File f, String title, String description, int orientation, Location loc) { ContentValues v = new ContentValues(); v.put(Images.Media.TITLE, title); v.put(Images.Media.DISPLAY_NAME, title); v.put(Images.Media.DESCRIPTION, description); v.put(Images.Media.ORIENTATION, orientation); String nameFile = f.getName(); File parent = f.getParentFile() ; String path = parent.toString().toLowerCase() ; String nameParent = parent.getName().toLowerCase() ; v.put(Images.ImageColumns.BUCKET_ID
  • Android - Why my saved image is not appearing in the default gallery of my phone?
    I am trying to save an image from my application to the default gallery of my phone. The code below works perfectly if I have a SD card on the phone. The image saved appears in the phone's gallery and everything, as expected: private Uri saveMediaEntry(File f, String title, String description, int orientation, Location loc) { ContentValues v = new ContentValues(); v.put(Images.Media.TITLE, title); v.put(Images.Media.DISPLAY_NAME, title); v.put(Images.Media.DESCRIPTION, description); v.put(Images.Media.ORIENTATION, orientation); String nameFile = f.getName(); File parent = f.getParentFile()
  • 无法在cocos2dx android中更改场景的背景(Not able to change the background of the scene in cocos2dx android)
    问题 我已经开始使用 cocos2dx 进行游戏开发。 并从 HelloWorld 示例游戏开始。 我能够运行这个示例游戏。 但是当我尝试更改背景颜色时,出现错误 **HelloWorldScene.h** The type 'HelloWorld' must implement the inherited pure virtual method 'cocos2d::CCRGBAProtocol::setOpacity' **Changes:** class HelloWorld : public cocos2d::CCLayerColor 并且也在 **HelloWorldScene.cpp** Invalid arguments ' Candidates are: bool initWithColor(const cocos2d::_ccColor4B &, ?, ?) bool initWithColor(const cocos2d::_ccColor4B &) ' **Changes:** CC_BREAK_IF(!CCLayerColor::initWithColor(ccc4(255,255,255,255))); 我是 cocos2dx 和 C++ 的新手。 还有什么要包括的吗? 请帮我解决这个问题。 谢谢。 编辑: HelloWorldScene.cpp
  • 将 ImageView 保存到 Android 模拟器库(Save ImageView to Android Emulator Gallery)
    问题 我想将图像保存到 Android Gallery,这是我当前的代码: image.setDrawingCacheEnabled(true); image.buildDrawingCache(true); Bitmap b = image.getDrawingCache(); if(!new File("/"+Environment.DIRECTORY_PICTURES).exists()) Log.e("Error","/"+Environment.DIRECTORY_PICTURES+" Dont exist"); File file = new File(Environment.DIRECTORY_PICTURES+"/myImage.jpg"); file.createNewFile(); FileOutputStream ostream = new FileOutputStream(file); b.compress(CompressFormat.JPEG, 80, ostream); image.setDrawingCacheEnabled(false); ostream.close(); Toast.makeText(Ads.this, "Offer saved", 1).show(); 它总是返回相同的错误: Error: /Pictures Dont
  • 保存到sdcard的图像未出现在Android的Gallery应用中(Image, saved to sdcard, doesn't appear in Android's Gallery app)
    问题 我将图像保存到sdcard中,直到我拔下sdcard并将其返回之前,它才出现在Gallery应用程序中。 你知道为什么会这样吗? 似乎Gallery应用程序具有一些在文件保存时未更新的缓存... 其实,我也想在Gallery应用程序中打开刚刚保存的图像,但没有成功这是我关于这个问题的问题。 回答1 安装SD卡后,系统会扫描SD卡以查找任何新的映像(和其他)文件。 如果要以编程方式添加文件,则可以使用此类: http://developer.android.com/reference/android/media/MediaScannerConnection.html 回答2 一个更简单的解决方案是使用静态便捷方法scanFile(): File imageFile = ... MediaScannerConnection.scanFile(this, new String[] { imageFile.getPath() }, new String[] { "image/jpeg" }, null); 如果this是您的活动(或任何上下文),则只有在您使用非标准文件扩展名且null为可选回调(对于这种简单情况我们不需要)的情况下,mime类型才是必需的。 回答3 我对原始问题以及可能存在此问题的其他人的回答: 我遇到了同样的问题
  • save the image to the gallery in android
    How can i save the image that the camera take into the gallery? i have this code but doesn't save the image private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents mCurrentPhotoPath = image.getAbsolutePath()
  • Image, saved to sdcard, doesn't appear in Android's Gallery app
    I save an image to the sdcard and it doesn't appear in the Gallery application until I pull off the sdcard and return it back. Do you have any idea why is it so? Seems like the Gallery application has some cache that isn't updated on file save... Actually, I also want to open the just-saved image in Gallery application and have no success with that this is my question about this issue.
  • Launching Intent.ACTION_VIEW intent not working on saved image file
    First of all let me say that this questions is slightly connected to another question by me. Actually it was created because of that. I have the following code to write a bitmap downloaded from the net to a file in the sd card: // Get image from url URL u = new URL(url); HttpGet httpRequest = new HttpGet(u.toURI()); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); InputStream instream = bufHttpEntity.getContent()
  • 如何在cocos2d-x中使用android ndk检查崩溃日志(How to check crash log using android ndk in cocos2d-x)
    问题 我使用cocos2d-x来开发游戏,在iOs中完美运行后,我转向了android平台。 但它在android的某个地方运行,并且我只收到一些错误日志,如下所示: 08-26 10:49:23.823: A/libc(2884): Fatal signal 11 (SIGSEGV) at 0x0000000c (code=1), thread 2917 (Thread-285) 有了这个,我无法修复崩溃日志。 所以我的问题是如何检查崩溃日志的堆栈? 在SO中,也有一些类似的问题,但是没有对我有用的答案。 使用ndk-stack读取崩溃日志 无法从android ndk中的堆栈跟踪中获取行号 如何获取有用的崩溃日志信息Android Cocos2dx C ++ 回答1 我在http://www.cocos2d-x.org/boards/6/topics/20437中找到了完美的答案。 解决方案是: 当您在LogCat上收到这样的错误时,它们将保存在$PROJECT_PATH/obj/local/armeabi ,其中$PROJECT_PATH是您的cocos2d-x android项目的路径。 要将消息符号化为可以理解的内容,可以使用ndk-stack工具。 打开终端(或不确定,Cygwin)并输入 cd $ANDROID_NDK adb logcat | ./ndk-stack