GVKun编程网logo

ImageIO.read返回NULL,没有错误(image.open()返回值)

6

以上就是给各位分享ImageIO.read返回NULL,没有错误,其中也会对image.open()返回值进行解释,同时本文还将给你拓展AndroidMediaProjectionacquisitio

以上就是给各位分享ImageIO.read返回NULL,没有错误,其中也会对image.open()返回值进行解释,同时本文还将给你拓展Android MediaProjection acquisitionLatestImage始终为ImageReader返回Null、Android-setImageBitmap(bmp)在创建视频缩略图后返回null、c# – ConfigurationManager.GetSection返回null、c# – Nhibernate GetById返回null的intInadad的ObjectNotFoundException等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

ImageIO.read返回NULL,没有错误(image.open()返回值)

ImageIO.read返回NULL,没有错误(image.open()返回值)

以下代码似乎不起作用,即使该文件看起来很好也是如此。

    images = new BufferedImage[32];    FileInputStream fis = null;    for (int i = 0; i < 32; i++) {        File file = new File("tiles\\"+i+".bmp");        if (!file.exists()){            System.out.println("File  "+i+" failed");        }        try {             fis = new FileInputStream(file);         } catch (FileNotFoundException e) {             System.err.println(e + "" + i);         }        try {             images[i] = ImageIO.read(fis);         } catch (IOException e) {             System.err.println(e + "" + i);         }        if (images[i] == null) {            System.out.println("Image "+i+" failed");        }    }

在此先感谢您的帮助。

编辑:结果是我试图去Graphics.drawImage(images [0]);,它给了我一个空指针异常。这段代码可以很好地完成。

编辑:更改按建议移动if(!file.exists()),并将文件包装在输入流中。

答案1

小编典典

ImageIO.read(file); 如果找不到注册的 ImageReader, 将返回null 。请检查您是否已注册任何
ImageReader

我认为此代码段可以帮助您

File file = new File("bear.jpg"); // I have bear.jpg in my working directory      FileInputStream fis = new FileInputStream(file);      BufferedImage image = ImageIO.read(fis); //reading the image file

您只需要将文件包装到 FileInputStream中 ,然后将其传递给 read()

Android MediaProjection acquisitionLatestImage始终为ImageReader返回Null

Android MediaProjection acquisitionLatestImage始终为ImageReader返回Null

如何解决Android MediaProjection acquisitionLatestImage始终为ImageReader返回Null?

我正在编写简单的Screenshot应用程序,并为此使用MediaProjection + ImageReader。我使用some sample解决此任务。
当我单击“捕获”按钮时,我总是在日志消息中得到"image: NULL"

ImageReader.newInstance中,我将格式设置为ImageFormat.RGB_565。默认值为0x1,但是当我使用此值时,会显示警告消息:

必须是以下之一:ImageFormat.UNKNowN,ImageFormat.RGB_565, ImageFormat.YV12,ImageFormat.Y8,ImageFormat.NV16,ImageFormat.NV21, ImageFormat.YUY2,ImageFormat.JPEG,ImageFormat.DEPTH_JPEG, ImageFormat.YUV_420_888,ImageFormat.YUV_422_888, ImageFormat.YUV_444_888,ImageFormat.FLEX_RGB_888, ImageFormat.FLEX_RGBA_8888,ImageFormat.RAW_SENSOR, ImageFormat.RAW_PRIVATE,ImageFormat.RAW10,ImageFormat.RAW12, ImageFormat.DEPTH16,ImageFormat.DEPTH_POINT_CLOUD, ImageFormat.PRIVATE,ImageFormat.HEIC

我的问题:为什么 ImageReader 中的 Image 总是 Null ?以及如何正确解决?谢谢

我的代码:

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.ImageFormat;
import android.hardware.display.displayManager;
import android.hardware.display.Virtualdisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.mediaprojectionmanager;
import android.os.Bundle;
import android.os.Environment;
import android.util.displayMetrics;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "test_t";

    private ImageReader mImageReader;
    private mediaprojectionmanager mmediaprojectionmanager;
    private Intent mCreateScreenCaptureIntent;
    private MediaProjection mMediaProjection;
    private Virtualdisplay mVirtualdisplay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View mBtnCapture = findViewById(R.id.btn_capture);
        mBtnCapture.setonClickListener(this);

        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tearDownMediaProjection();
    }

    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        mMediaProjection = mmediaprojectionmanager.getMediaProjection(resultCode,data);
        if (mMediaProjection != null) {
            startScreenCapture();
            takeCapture();
            stopScreenCapture();
        }
    }

    @Override
    public void onClick(View v) {
        startActivityForResult(mCreateScreenCaptureIntent,777);
    }

    private void init() {
        displayMetrics displayMetrics = getResources().getdisplayMetrics();
        mImageReader = ImageReader.newInstance(displayMetrics.widthPixels,displayMetrics.heightPixels,ImageFormat.RGB_565,2); // format 0x1

        mmediaprojectionmanager = (mediaprojectionmanager) getSystemService(MEDIA_PROJECTION_SERVICE);
        mCreateScreenCaptureIntent = mmediaprojectionmanager.createScreenCaptureIntent();
    }

    private void startScreenCapture() {
        if (mMediaProjection == null)
            return;

        displayMetrics displayMetrics = getResources().getdisplayMetrics();
        mVirtualdisplay = mMediaProjection.createVirtualdisplay(
                "ScreenCapture",displayMetrics.widthPixels,displayMetrics.densityDpi,displayManager.VIRTUAL_disPLAY_FLAG_AUTO_MIRROR,mImageReader.getSurface(),null,null);
    }

    private void stopScreenCapture() {
        if (mVirtualdisplay == null) {
            return;
        }
        mVirtualdisplay.release();
        mVirtualdisplay = null;
    }

    private void takeCapture() {
        Image image = mImageReader.acquireLatestimage();
        if (image == null) {
            Log.d(TAG,"image: NULL");
            return;
        }

        int width = image.getWidth();
        int height = image.getHeight();
        final Image.Plane[] planes = image.getPlanes();
        final ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = planes[0].getRowStride();
        int rowPadding = rowStride - pixelStride * width;
        Bitmap mBitmap = Bitmap.createBitmap(width + rowPadding / pixelStride,height,Bitmap.Config.ARGB_8888);
        mBitmap.copyPixelsFromBuffer(buffer);
        mBitmap = Bitmap.createBitmap(mBitmap,width,height);
        image.close();
        saveBitmapToFile(mBitmap);
    }

    private void saveBitmapToFile(Bitmap bitmap) {
        File directory = new File(Environment.getExternalStorageDirectory(),"SCREEN_TEMP");
        if (!directory.exists())
            directory.mkdirs();
        String name = "shot" + new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date()) + "." + Bitmap.CompressFormat.PNG.toString();
        File file = new File(directory,name);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG,100,out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printstacktrace();
        }
    }

    private void tearDownMediaProjection() {
        if (mMediaProjection != null) {
            mMediaProjection.stop();
            mMediaProjection = null;
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Android-setImageBitmap(bmp)在创建视频缩略图后返回null

Android-setImageBitmap(bmp)在创建视频缩略图后返回null

如何解决Android-setImageBitmap(bmp)在创建视频缩略图后返回null?

我使用ThumbnailUtils.createVideoThumbnail()函数已经有好几年了,但是突然之间我不明白为什么它停止工作了。我有这样的视频路径(用VideoCompressor库压缩后得到):

 /storage/emulated/0/com.xscoder.appname/media/videos/VIDEO_20200918_145357.mp4

这是我的videoToSendURL变量。

因此,我使用以下代码显示视频的缩略图:

Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoToSendURL,MediaStore.Images.Thumbnails.MINI_KIND);
    if (thumb != null) {
        Log.i(TAG,"Thumb: " + thumb.getByteCount());
        myImageView.setimageBitmap(thumb);
    } else { Log.i("Something went wrong."); }

Logcat打印出:

THUMB: 294912

但是该应用程序崩溃了,我得到了以下致命异常:

Attempt to invoke virtual method ''void android.widget.ImageView.setimageBitmap(android.graphics.Bitmap)'' on a null object reference

我假设我的thumb位图不为空,因为Logcat返回了它的byteCount数据,并且我知道myImg不为空,我已经在onCreate()中声明了它。

-更新-

我真正需要做的是创建一个视频缩略图以将其上传到服务器,所以这是我使用的代码:

外部VideCompressor类,代码位于公共类XServerSDK扩展了Application {}

public static class VideoCompressor extends AsyncTask<String,String,String> {
      @SuppressLint("StaticFieldLeak")
      Context ctx;
      VideoCompressor(Context context){ ctx = context; }

      @Override protected void onPreExecute() {
         super.onPreExecute();
         showHUD(ctx);
         Toast.makeText(ctx,"Compressing Video...",Toast.LENGTH_LONG).show();
      }

      @Override
      protected String doInBackground(String... paths) {
         String filePath = null;
         try { filePath = KplCompressor.with(ctx).compressVideo(paths[0],paths[1]);
         } catch (URISyntaxException e) { e.printstacktrace();
            Log.i(TAG,"ERROR ON VIDEO COMPRESSOR: " + e.getMessage());
         }
         return  filePath;
      }
      @Override
      protected void onPostExecute(String compressedFilePath) {
         super.onPostExecute(compressedFilePath);

         File imageFile = new File(compressedFilePath);
         float length = imageFile.length() / 1024f; // Size in KB
         String videoSize;
         if(length >= 1024) { videoSize = length / 1024f + " MB";
         } else { videoSize = length + " KB"; }

         videoToSendURL = compressedFilePath;
         Log.i(TAG,"COMpressed VIDEO -> URL: " + videoToSendURL + " -> SIZE: " + videoSize);

        // HERE I CALL MY FUNCTION THAT''S IN MY Messages ACTIVITY
        new Messages().uploadFiles();

      }
   }

消息活动中:

void uploadFiles() {
      // Video
        XsuploadFile(videoToSendURL,"video.mp4",(Activity)ctx,new XServerSDK.XSFileHandler() {
        @Override public void done(final String vidURL,String e) {
            if (vidURL != null) {
                Log.i(TAG,"VIDEO URL: " + vidURL);
                // Create VideoThumbnail
                 Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoToSendURL,MediaStore.Images.Thumbnails.MINI_KIND);
                  if (thumb != null) {
                      Log.i(TAG,"videoToSendURL: " + videoToSendURL);
                      Log.i(TAG,"THUMB: " + thumb.getByteCount());
                      
                      // VideoThumb
                      String imgPath = getFilePathFromURI(getimageUri(thumb,ctx),ctx);
                      Log.i(TAG,"imgPath: " + imgPath);
                      XsuploadFile(imgPath,"image.jpg",(Activity) ctx,new XServerSDK.XSFileHandler() { @Override public void done(final String thumbURL,String e) { 
        if (thumbURL != null) { 
            Log.i(TAG,"VIDEO THUMB URL: " + thumbURL);
            if (vidURL.contains("upload_max_filesize")) {
                hideHUD();   
                simpleAlert("The uploaded file exceeds the upload_max_filesize directive and cannot be uploaded.",ctx);
           } else { 
              fileType = "video"; 
              sendMessage(thumbURL,vidURL,"","");
           } 
           // error
           } else { hideHUD(); simpleAlert(e,ctx);
    }}});// ./ XsuploadFile
        
    } else { hideHUD(); simpleAlert("Something went wrong,try again.",ctx); }
    
      // error
      } else { hideHUD(); simpleAlert(e,ctx); }
    }});// ./ XsuploadFile
}

这是我从Uri获取真实路径的代码:

//-----------------------------------------------
   // MARK - GET URI OF A STORED IMAGE
   //-----------------------------------------------
   public static Uri getimageUri(Bitmap bm,Context ctx) {
      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
      bm.compress(Bitmap.CompressFormat.JPEG,100,bytes);
      String path = MediaStore.Images.Media.insertimage(ctx.getContentResolver(),bm,"image",null);
      return Uri.parse(path);
   }


   //-----------------------------------------------
   // MARK - GET REAL PATH FROM URI
   //-----------------------------------------------
   public static String getFilePathFromURI(Uri uri,Context ctx) {
      @SuppressLint("Recycle")
      Cursor cursor = ctx.getContentResolver().query(uri,null,null);
      assert cursor != null;
      cursor.movetoFirst();
      int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
      return cursor.getString(idx);
   }

最后,致命异常:

java.lang.NullPointerException: Attempt to invoke virtual method ''android.content.ContentResolver android.content.Context.getContentResolver()'' on a null object reference
        at android.content.Contextwrapper.getContentResolver(Contextwrapper.java:103)
        at com.xscoder.hi.XServerSDK.getimageUri(XServerSDK.java:1253)
        at com.xscoder.hi.Messages$16.done(Messages.java:1403)

因此,在这种情况下,代码在到达以下位置时会崩溃:

 String imgPath = getFilePathFromURI(getimageUri(thumb,ctx);

以前从未发生过,也许是因为我正在从uploadFiles()类中调用VideoCompressor函数吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

c# – ConfigurationManager.GetSection返回null

c# – ConfigurationManager.GetSection返回null

这是我的app.config
<configuration>
  <configSections>
      <section name="procedureList" type="System.Configuration.NameValueSectionHandler,System,Version=4.0.30319,Culture=neutral,PublicKeyToken=b77a5c561934e089"/>
  </configSections>

  <procedureList>
    <add key="NAS.spBusObjGetLineProd" value="@area='Melt Shop';@endDt=?date?;@dayonly=1;@obj='Melt Shop Business Objective" />
    <add key="NAS.spBusObjGetLineProd" value="@area='Cold Mill';@endDt=?date?;@dayonly=1;@obj='Cold Mill Business Objective" /> 
  </procedureList>
  <appSettings>
    <add key="Connstr" value=""/>
    <add key="Userid" value=""/>
    <add key="Timeout" value=""/>
  </appSettings>

</configuration>

但是当我在代码中调用它时,我得到一个null

public void samplemethod()
{
    NameValueCollection nvc = ConfigurationManager.GetSection("procedureList") as NameValueCollection;
    string[] keys = nvc.AllKeys;
}

我会感谢任何帮助指出我做错了什么

解决方法

Using section handlers to group settings in the configuration file

例如,您可以按照以下内容进行操作

private void ReadSettings()
{
    NameValueCollection loc = 
   (NameValueCollection )ConfigurationSettings.GetConfig("procedureList");
}

MSDN ConfigurationManager.GetConfig Method

c# – Nhibernate GetById返回null的intInadad的ObjectNotFoundException

c# – Nhibernate GetById返回null的intInadad的ObjectNotFoundException

我正在使用流利的Nhibernate.此代码根据其ID从DB加载类型T的实例.
public T GetById(IdT id,bool shouldLock)
    {
        T entity;

        if (shouldLock)
        {
            entity = (T) NHibernateSession.Load(persitentType,id,LockMode.Upgrade);
        }
        else
        {
            entity = (T) NHibernateSession.Load(persitentType,id);
        }

        return entity;
    }

但我有很大的问题.当我调用属性时,我得到ObjectNotFoundException而不是null.

如何使该实体可以为空并且不返回异常?

解决方法

我会使用Get而不是Load. Get将返回null,而不是异常.

今天关于ImageIO.read返回NULL,没有错误image.open()返回值的讲解已经结束,谢谢您的阅读,如果想了解更多关于Android MediaProjection acquisitionLatestImage始终为ImageReader返回Null、Android-setImageBitmap(bmp)在创建视频缩略图后返回null、c# – ConfigurationManager.GetSection返回null、c# – Nhibernate GetById返回null的intInadad的ObjectNotFoundException的相关知识,请在本站搜索。

本文标签: