The exponential increase in new coronavirus disease 2019 cases and deaths has made COVID-19 the leading cause of death in many countries. Thus, in this study, we propose an efficient technique for the automatic detection of COVID-19 and pneumonia based on X-ray images. A stacked denoising convolutional autoencoder (SDCA) model was proposed to classify X-ray images into three classes: normal, pneumonia, and COVID-19. The SDCA model was used to obtain a good representation of the input data and extract the relevant features from noisy images. The proposed model's architecture mainly composed of eight autoencoders, which were fed to two dense layers and SoftMax classifiers. The proposed model was evaluated with 6356 images from the datasets from different sources. The experiments and evaluation of the proposed model were applied to an 80/20 training/validation split and for five cross-validation data splitting, respectively. The metrics used for the SDCA model were the classification accuracy, precision, sensitivity, and specificity for both schemes. Our results demonstrated the superiority of the proposed model in classifying X-ray images with high accuracy of 96.8%. Therefore, this model can help physicians accelerate COVID-19 diagnosis.